Type definition in object literal in TypeScript

后端 未结 9 2528
粉色の甜心
粉色の甜心 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 = {
      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 = {
      property: "my prop",
      property2: "my second prop", // TS Error: Type '"my second prop"' is not assignable to type 'Values'.
    };
    

提交回复
热议问题