Typescript 使用另一种类型所需的键创建类型

d-_*_*_-b 1 javascript typescript

我有以下type定义:

export type colors = "red" | "blue" | "green"

export interface details {
   name: string;
   id: string;
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以定义一个需要type定义所有 3 个对象的方法,而不必显式地循环遍历每个对象?

export interface allColors {
   red: details;
   blue: details;
   ... etc.
}
Run Code Online (Sandbox Code Playgroud)

与此相反,type这使得按键可选?

export type allColors =  {
    [key in colors]: details;
};
Run Code Online (Sandbox Code Playgroud)

Won*_*Hau 5

您可以通过使用类型别名记录类型来实现此目的。

export type colors = "red" | "blue" | "green"

export interface details {
   name: string;
   id: string;
}

export type allColors = Record<colors, details> 

// Usage
const x: allColors = { // type error, missing properties: 'blue', 'green'
  red: {
    name: 'red',
    id: '1'
  }
}
Run Code Online (Sandbox Code Playgroud)

假设您想覆盖某些键的类型,比如说您想要green: number代替,您可以使用ExcludeIntersection Typesgreen: details来实现这一点:

export type allColors = Record<Exclude<colors, 'green'>, details> & {green: string}

// Usage
const x: allColors = { 
  red: {
    name: 'red',
    id: '1'
  },
  green: 'hello' // No error
}
Run Code Online (Sandbox Code Playgroud)