首页 > 解决方案 > 如何基于字符串数组制作对象类型/接口

问题描述

我从网络调用中获取了一些 JSON 对象,形状如下:

{
  timestamp: "1636814680595",
  price: "$1",
  ...manyOtherKeys
}

所有值都是字符串。

我想创建一个基于预期键数组的接口。由此:

const expectedKeys = ['timestamp', 'price', ...]

我想以编程方式生成类型(或接口):

type ExpectedType {
  timestamp: string, 
  price: string
}

有没有简单的方法可以做到这一点?目前,我能想到的只有以下内容,这似乎是做作的:

// I did not find a way to start from an array and reduce it to this object
// while preserving the type. I'm okay starting with this object instead of
// an array of string. 
const objectWithExpectedShape = {
  timestamp: '',
  price: '',
}
type ExpectedType = typeof objectWithExpectedShape;

标签: typescript

解决方案


你想要的只有在expectedKeys静态的情况下才有可能 - 如果你对它进行硬编码。(如果它们是动态生成的并且不存在于源代码中,那是不可能的,因为 TypeScript 类型仅对编译时存在的内容进行操作 - 在运行时,您只剩下纯 JavaScript)

定义数组as const,使其不会扩大到string[],然后您可以制作一个由键(数组项)和 组成的记录string

const expectedKeys = ['timestamp', 'price'] as const;
type ExpectedType = Record<
    typeof expectedKeys[number],
    string
>;

推荐阅读