TypeScript and field initializers

前端 未结 14 2264
暖寄归人
暖寄归人 2020-11-30 16:49

How to init a new class in TS in such a way (example in C# to show what I want):

// ... some code before
return new MyClass { Field         


        
14条回答
  •  死守一世寂寞
    2020-11-30 17:20

    You can affect an anonymous object casted in your class type. Bonus: In visual studio, you benefit of intellisense this way :)

    var anInstance: AClass =  {
        Property1: "Value",
        Property2: "Value",
        PropertyBoolean: true,
        PropertyNumber: 1
    };
    

    Edit:

    WARNING If the class has methods, the instance of your class will not get them. If AClass has a constructor, it will not be executed. If you use instanceof AClass, you will get false.

    In conclusion, you should used interface and not class. The most common use is for the domain model declared as Plain Old Objects. Indeed, for domain model you should better use interface instead of class. Interfaces are use at compilation time for type checking and unlike classes, interfaces are completely removed during compilation.

    interface IModel {
       Property1: string;
       Property2: string;
       PropertyBoolean: boolean;
       PropertyNumber: number;
    }
    
    var anObject: IModel = {
         Property1: "Value",
         Property2: "Value",
         PropertyBoolean: true,
         PropertyNumber: 1
     };
    

提交回复
热议问题