typescriptsyntaxinstanceinstantiation

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


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,
 );

Solution

  • 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/2/everyday-types.html#type-assertions