问题
假设我们有一个对象
export const fruitCounts = {
pear: 5,
apple: 9,
banana: 3
}
然后需要定义一个类型,该类型为此对象所有属性的联合类型:
type SingleFruitCount = { pear: number } | { apple: number } | { banana: number }
那么该怎么通过对象 fruitCounts
直接生成 SingleFruitCount
类型呢?
解答
首先我们先拿到 fruitCounts
的类型
type FruitCounts = typeof fruitCounts
如果我们这样定义SingleFruitCount
type SingleFruitCount = {
[Key in keyof FruitCounts]: {}
}
其等同于:
type SingleFruitCount = {
pear: {};
apple: {};
banana: {};
}
我们继续修改 SingleFruitCount
定义
type SingleFruitCount = {
[Key in keyof FruitCounts]: {
[K in Key]: number
}
}
此时效果会变成:
type SingleFruitCount = {
pear: {
pear: number;
};
apple: {
apple: number;
};
banana: {
banana: number;
};
}
那这个时候我们只需要把每个对象通过 key
取出来即可:
type SingleFruitCount = {
[Key in keyof FruitCounts]: {
[K in Key]: number
}
}[keyof FruitCounts]
完整代码:
export const fruitCounts = {
pear: 5,
apple: 9,
banana: 3
}
type FruitCounts = typeof fruitCounts
type SingleFruitCount = {
[Key in keyof FruitCounts]: {
[K in Key]: number
}
}[keyof FruitCounts]