簡體   English   中英

Typescript:如何將鍵數組轉換為聯合類型的對象?

[英]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的類型。

你想要一個映射類型。

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中的鍵,並為每個鍵創建一個新的 object 類型。

SET_PROPERTY_PAYLOAD應該與上面的長格式版本完全相同。

見游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM