首页 > 解决方案 > 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 上的字符串并期望它是一个数字

有什么解决办法吗?

谢谢!

标签: typescripttypescript-typings

解决方案


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
});

推荐阅读