Type definition in object literal in TypeScript

后端 未结 9 2377
粉色の甜心
粉色の甜心 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 09:54

    If your properties have the same type, you could use predefined utility type Record :

    type Keys = "property" | "property2"
    
    const obj: Record<Keys, string> = {
      property: "my first prop",
      property2: "my second prop",
    };
    

    You can of course go further and define a custom type for your property values:

    type Keys = "property" | "property2"
    type Values = "my prop" | "my other allowed prop"
    
    const obj: Record<Keys, Values> = {
      property: "my prop",
      property2: "my second prop", // TS Error: Type '"my second prop"' is not assignable to type 'Values'.
    };
    
    0 讨论(0)
  • 2020-11-27 09:56

    In TypeScript if we are declaring object then we'd use the following syntax:

    [access modifier] variable name : { /* structure of object */ }
    

    For example:

    private Object:{ Key1: string, Key2: number }
    
    0 讨论(0)
  • 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" };
    
    0 讨论(0)
提交回复
热议问题