[英]Typescript: How to convert an array of keys into a union type of objects?
1. 字符串數組 -> 字符串聯合(有效)
我看到一個解決方案從字符串數組創建字符串文字的聯合。
const keys = ["cat", "dog"] as const;
type Keys = typeof keys[number]; // "name" | "age"
2. 字符串數組 -> 對象聯合(有可能嗎?)
我的問題是是否可以從字符串數組創建對象聯合? 下面的代碼有效,我只想用keyof IObject
之類的東西縮短SET_PROPERTY_PAYLOAD
並從那里生成 object 類型的聯合。
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
的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.