TypeScript and field initializers

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

    if you want to create new instance without set initial value when instance

    1- you have to use class not interface

    2- you have to set initial value when create class

    export class IStudentDTO {
     Id:        number = 0;
     Name:      string = '';
    
    
    student: IStudentDTO = new IStudentDTO();
    
    0 讨论(0)
  • 2020-11-30 17:37

    I suggest an approach that does not require Typescript 2.1:

    class Person {
        public name: string;
        public address?: string;
        public age: number;
    
        public constructor(init:Person) {
            Object.assign(this, init);
        }
    
        public someFunc() {
            // todo
        }
    }
    
    let person = new Person(<Person>{ age:20, name:"John" });
    person.someFunc();
    

    key points:

    • Typescript 2.1 not required, Partial<T> not required
    • It supports functions (in comparison with simple type assertion which does not support functions)
    0 讨论(0)
提交回复
热议问题