Type definition in object literal in TypeScript

后端 未结 9 2544
粉色の甜心
粉色の甜心 2020-11-27 09:29

In TypeScript classes it\'s possible to declare types for properties, for example:

class className {
  property: string;
};

How do declare

9条回答
  •  悲哀的现实
    2020-11-27 10:03

    You're pretty close, you just need to replace the = with a :. You can use an object type literal (see spec section 3.5.3) or an interface. Using an object type literal is close to what you have:

    var obj: { property: string; } = { property: "foo" };
    

    But you can also use an interface

    interface MyObjLayout {
        property: string;
    }
    
    var obj: MyObjLayout = { property: "foo" };
    

提交回复
热议问题