How to instantiate an object in TypeScript by specifying each property and its value?

YSA picture YSA · Apr 10, 2017 · Viewed 22.7k times · Source

Here's a snippet in which I instantiate a new content object in my service:

const newContent = new Content(
     result.obj.name
     result.obj.user.firstName,
     result.obj._id,
     result.obj.user._id,
);

The problem is that this way of object instantiation relies on the order of properties in my content model. I was wondering if there's a way to do it by mapping every property to the value I want to set it to, for example:

 const newContent = new Content(
     name: result.obj.name,
     user: result.obj.user.
     content_id: result.obj._id,
     user_id: result.obj.user._id,
 );

Answer

Geoff Lentsch picture Geoff Lentsch · Jul 27, 2017
const newContent = <Content>({
    name: result.obj.name,
    user: result.obj.user.
    content_id: result.obj._id,
    user_id: result.obj.user._id,
 });

Here you can instantiate an object and use type assertion or casting to the Content type. For more information on type assertion: https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions