How to build a TypeScript class constructor with object defining class fields?

后端 未结 2 802
耶瑟儿~
耶瑟儿~ 2020-12-15 18:11

In TypeScript it\'s possible to create a class with a constructor that takes parameter with access modifiers and it automatically convert those parameters in class fields.

2条回答
  •  心在旅途
    2020-12-15 18:47

    You can achieve similar behavior by creating an interface:

    interface IProps {
      id: number;
      updatedAt: number;
      createdAt: number;
    }
    
    class Item {
      constructor(public props: IProps) {}
    }
    
    const item = new Item({ id: 1, updatedAt: 1, createdAt: 1 });
    console.log(item.props.id);
    

提交回复
热议问题