typescript - 如何基于字符串数组制作对象类型/接口
问题描述
我从网络调用中获取了一些 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;
解决方案
你想要的只有在expectedKeys
静态的情况下才有可能 - 如果你对它进行硬编码。(如果它们是动态生成的并且不存在于源代码中,那是不可能的,因为 TypeScript 类型仅对编译时存在的内容进行操作 - 在运行时,您只剩下纯 JavaScript)
定义数组as const
,使其不会扩大到string[]
,然后您可以制作一个由键(数组项)和 组成的记录string
。
const expectedKeys = ['timestamp', 'price'] as const;
type ExpectedType = Record<
typeof expectedKeys[number],
string
>;
推荐阅读
- ios - 如何使用 SwiftUI 处理嵌套的 TabView?
- python - 一个程序来检查一个反转的字符串是否是回文或不在 python 中使用 Stack Machine
- bluetooth-lowenergy - 蓝牙 5.2 广告和扫描响应
- python - Python 库“单击”将参数传递给函数
- python - 如何在闭合曲线的质心上找到最小/最大轴长度
- r - 如何进行与行具有的特定变量的值一样多次的特定于行的迭代计算?
- mongodb - 错误:在 docker 中运行的 mongodb 4.4.4 中的身份验证失败
- flutter - 如何避免“空检查运算符使用空值” Flutter Firestore
- google-apps-script - 谷歌表格自动选择下拉第一项
- angular - 对象数组的角度定位