arrays - typescript :如何将键数组转换为联合类型的对象?

标签 arrays typescript typescript-generics union-types narrowing

<强>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 的类型。

最佳答案

你想要a mapped type.

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 应该与上面的长格式版本完全相同。

See Playground

关于arrays - typescript :如何将键数组转换为联合类型的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73481919/

相关文章:

arrays - 重新组合 Numpy 数组中的条目

c# - 查找排序数组中的所有差异

typescript 没有正确进行案例分析

typescript - 如何使用重载定义函数以恰好具有 1 或 2 个参数,其类型取决于所使用的字符串文字

Angular 6 子路由不起作用

typescript - 如何使用 "p-waterfall"TypeScript 类型

java - 使用 onItemClickListener 的数组位置

c - 结构体入口声明了一个数组类型的字段,但编译器说它是一个指针

typescript - VS Code : Type 'ArrayConstructor' is missing the following properties from type 'MyCustomType[]' 中的 Vue Array Prop JSDoc TypeScript 错误

typescript 重复标识符 'Node'