<强>1。字符串数组 -> 字符串并集(有效)
我看到一个解决方案从字符串数组创建字符串文字的并集。
const keys = ["cat", "dog"] as const;
type Keys = typeof keys[number]; // "name" | "age"
<强>2。字符串数组 -> 对象并集(这可能吗?)
我的问题是是否可以从字符串数组中创建对象的并集?下面的代码有效,我只想用 keyof IObject
之类的东西缩短 SET_PROPERTY_PAYLOAD
并从那里生成对象类型的联合。
interface IObject = {
id: string;
name: string;
age: number;
}
// Is it possible to shorten this type using typescript's primitives
type SET_PROPERTY_PAYLOAD =
| {
id: string;
propertyName: "id"; // keyof IObject at index 0
value: string; // IObject["id"]
}
| {
id: string;
propertyName: "name"; // keyof IObject at index 1
value: string; // IObject["name"]
}
| {
id: string;
propertyName: "age"; // keyof IObject at index 2
value: number; // IObject["age"]
};
我的目标是通过从 propertyName
的当前值推断来缩小 value
的类型。
最佳答案
interface IObject {
id: string;
name: string;
age: number;
}
type SET_PROPERTY_PAYLOAD = {
[K in keyof IObject]: {
id: string,
propertyName: K,
value: IObject[K]
}
}[keyof IObject]
此类型映射 IObject
中的键并为每个键创建一个新的对象类型。
SET_PROPERTY_PAYLOAD
应该与上面的长格式版本完全相同。
关于arrays - typescript :如何将键数组转换为联合类型的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73481919/