Expression to create object implementing interface in typescript could be written in two statements (create + return):
=>
{
const obj: IStudent = { Id: 1, name: 'Naveed' };
return obj;
}
Is it possible to accomplish this in one statement / expression?
Something like this, for example:
=> return (_: IStudent = { Id: 1, name: 'Naveed' })
>Solution :
You can’t add a type in a return statement (there is a proposal to add a different type assertion that allows checking but does not force a specific type, as described here but that is not yet part of the language).
You could however add a return type to your arrow function: `(): IStudent => ({ Id: 1, name: ‘Naveed’ })
You could also create a helper function to help with creating such objects:
function asType<T>(value: T) {
return value;
};
type IStudent = { Id: number, name: string}
let fn = () => asType<IStudent>({ Id: 1, name: 'Naveed' });
Note: A regular type assertion (with as or <>) will type the object but might also allow unintended error to slip through (such as excess properties), although it might still be a decent option in some cases:
function asType<T>(value: T) {
return value;
};
type IStudent = { Id: number, name: string}
let fn = () => ({ Id: 1, name: 'Naveed', wops: "" }) as IStudent;