假设我有以下打字稿代码:
type fruit = "apple" | "banana" | "pear"
type color = "red" | "yellow" | "green"
Run Code Online (Sandbox Code Playgroud)
我想创建一个类型,该类型具有每种水果的数字属性和每种颜色的布尔属性,例如
type FruitsAndColors = {
[key in fruit]: number;
[key in color]: boolean
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,此错误并显示消息“映射类型可能无法声明属性或方法”,但它可以正常编译。这里到底发生了什么?
我可以用类似的方法来解决这个问题
type FruitsAndColors = {
[key in fruit]: number;
} & {
[key in color]: boolean
}
Run Code Online (Sandbox Code Playgroud)
但我想知道真正的问题是什么。
它不是“vscode 的 typescript 扩展”,而是TypeScript。它不允许您在单个type构造中执行两个映射。只是构造的语法不允许这样做。
相反,你按照你所展示的去做:
type FruitsAndColors = {
[key in fruit]: number;
} & {
[key in color]: boolean
};
Run Code Online (Sandbox Code Playgroud)
但请注意,该类型要求对象中存在所有六个属性。也许这就是您想要的,但如果不是,请?在映射的键后面添加(或将整个内容包装在 中Partial<>):
type FruitsAndColors = {
[key in fruit]?: number;
} & {
[key in color]?: boolean
};
// Or
type FruitsAndColors = Partial<{
[key in fruit]: number;
} & {
[key in color]: boolean
}>;
Run Code Online (Sandbox Code Playgroud)
您还可以使用条件类型:
type FruitsAndColors = Partial<{
[Key in (Fruit | Color)]: Key extends Fruit ? number : Key extends Color ? boolean : never;
}>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2816 次 |
| 最近记录: |