In a return statement, you cannot add a type directly (although there is a proposal for a different type assertion that allows checking without enforcing a specific type yet incorporated into the language).
However, you can specify a return type for your arrow function: `(): IStudent => ({ Id: 1, name: 'Naveed' })
You can also create a helper function to assist in creating such objects:
function asType<T>(value: T) {
return value;
};
type IStudent = { Id: number, name: string}
let fn = () => asType<IStudent>({ Id: 1, name: 'Naveed' });
Playground Link
Please note: Using regular type assertions like as
or <>
will type the object but may allow unintended errors to slip through, such as excess properties. It can still be an option in certain cases:
function asType<T>(value: T) {
return value;
};
type IStudent = { Id: number, name: string}
let fn = () => ({ Id: 1, name: 'Naveed', wops: "" }) as IStudent;
Playground Link