23

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,
 );
YSA
  • 799
  • 1
  • 12
  • 30

2 Answers2

23
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

Geoff Lentsch
  • 1,054
  • 11
  • 17
  • 1
    It is clear what you have changed, but it would be useful to say why. Teaching moments everywhere. – Anthony Horne Jul 27 '17 at 06:35
  • 30
    This is actually very very wrong! You're not instantiating an instance of `Content` here, you are creating a simple object which has the same members. If for example `Content` would have a method `fn`, then in your example this will fail: `newContent.fn()`. – Nitzan Tomer Sep 02 '18 at 14:07
  • 2
    this answer will work if you extend the prototype of the object like so: `const newContent = (_.extend({...}, Content.prototype));` – logeyg Oct 11 '18 at 20:11
  • As noted earlier, this would only work for an interface, which is what I'm using it for. – shturm Dec 02 '22 at 16:17
12

You can pass an object to the constructor which wraps all of those variables:

type ContentData = {
    name: string;
    user: string;
    content_id: string;
    user_id: string;
}

class Content {
    constructor(data: ContentData) {
        ...
    }
}

And then:

const newContent = new Content({
     name: result.obj.name,
     user: result.obj.user.
     content_id: result.obj._id,
     user_id: result.obj.user._id,
});
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299