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)
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代替,您可以使用Exclude和Intersection 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)
| 归档时间: |
|
| 查看次数: |
1608 次 |
| 最近记录: |