TypeScript and field initializers

前端 未结 14 2298
暖寄归人
暖寄归人 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:14

    I'd be more inclined to do it this way, using (optionally) automatic properties and defaults. You haven't suggested that the two fields are part of a data structure, so that's why I chose this way.

    You could have the properties on the class and then assign them the usual way. And obviously they may or may not be required, so that's something else too. It's just that this is such nice syntactic sugar.

    class MyClass{
        constructor(public Field1:string = "", public Field2:string = "")
        {
            // other constructor stuff
        }
    }
    
    var myClass = new MyClass("ASD", "QWE");
    alert(myClass.Field1); // voila! statement completion on these properties
    

提交回复
热议问题