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

前端 未结 2 1979
后悔当初
后悔当初 2020-12-14 20:20

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

const newContent = new Content(
     result.obj.name
     result.ob         


        
相关标签:
2条回答
  • 2020-12-14 20:55

    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,
    });
    
    0 讨论(0)
  • 2020-12-14 20:58
    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

    0 讨论(0)
提交回复
热议问题