typescript - Typescript - 具有已知键的键/值类型
问题描述
我有一个看起来像这样的对象:
const o: A = {
id: 'foo',
key1: 123,
key2: 456
}
id
是 type 的已知且必需的属性string
。其他键是动态的并且是数字。
如何在打字稿中定义这个?
我已经尝试过了:
type A = {
id: string;
[key: string]: number
} // Doesn't work
或这个
type A = {
id: string
} & {
[key: string]: number
} // Doesn't work either
TS 不会接受 ID 上的字符串并期望它是一个数字
有什么解决办法吗?
谢谢!
解决方案
type MyObject<K extends keyof any> = { id: string } & Record<Exclude<K, "id">, number>;
function myObjectWrapper<T extends MyObject<keyof T>>(metrics: T): MyObject<keyof T> {
return metrics;
}
const a = myObjectWrapper({
id: "foo",
key1: 123,
key2: 456
});
推荐阅读
- php - PHP时间特定的div显示
- blockchain - 以太坊 geth 无法连接到 bootnode 以访问私有以太坊网络
- r - R / quastrat / applyStrategy
- javascript - 角度:EventEmitter 在嵌入式组件中未定义
- apache - 通过 Maven 安装 Apache Stanbol
- xamarin - Xamarin Forms - iOS 上的键盘覆盖条目(文本字段)
- r - 如何找到按R中的因子排序的列的最大值?
- optimization - 优化 Google Apps 脚本中的读/写
- php - Apache 或 php.ini 配置以允许使用 phpspreadsheet 保存文件
- java - 我将如何测试鼠标光标位置与玩家的角度是否(相对)与实体相同?