Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shortest expression in typescript to create object implementing interface

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading