0

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' })
1

1 Answer 1

3

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' });

Playground Link

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;

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.