Type definition in object literal in TypeScript

后端 未结 9 2545
粉色の甜心
粉色の甜心 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条回答
  •  猫巷女王i
    2020-11-27 09:42

    In your code:

    var obj = {
      myProp: string;
    };
    

    You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):

    var string = 'A string';
    
    var obj = {
      property: string
    };
    

    However, what you want is that the object literal is typed. This can be achieved in various ways:

    Interface:

    interface myObj {
        property: string;
    }
    
    var obj: myObj = { property: "My string" };
    

    Type alias:

    type myObjType = {
        property: string
    };
    
    var obj: myObjType = { property: "My string" };
    

    Object type literal:

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

提交回复
热议问题