typescript - 如何获取对象数组中给定对象键的所有文字值的并集?
问题描述
假设我有这个对象数组,作为静态数据(它在运行时永远不会改变):
const things = [
{ id: 'some-id-1', value: 3 },
{ id: 'some-id-2', value: 7 },
{ id: 'some-id-3', value: 7 },
]
我想要这样的类型:
type ThingId = 'some-id-1' | 'some-id-2' | 'some-id-3'
有没有办法从对象数组中推断出来? ThingId
为什么我希望能够做到这一点:所以我可以创建类似 的函数doSomethingWithThing(thingId: ThingId)
,TypeScript 强制它只能使用有效的 调用ThingId
,而不是使用 any string
。
解决方案
推荐阅读
- c - 如何通过if语句获取用户信息?
- ios - window?.subviews[1] 应用程序在 iOS 13 中崩溃
- python - 第二次执行os.walk时找不到目录
- apache - 搞砸了 url 重写
- python - 自动 Webscrape Bloominberg
- angular - firestore .update() 在服务器中以角度完成后如何运行代码
- python - 没有numpy,无法在python的二维矩阵中打印第一行或第一列名称。只会打印矩阵中的浮点数
- javascript - 无法读取未定义的属性“toString”,但函数接受我使用定义的 toString() 方法创建的类
- sql - 如何计算每条记录的空列
- java - 使用 Spring 表单更新后如何防止 POJO 中预先存在的对象引用变为空