簡體   English   中英

Typescript - 具有已知鍵的鍵/值類型

[英]Typescript - Key/value type with known keys

我有一個看起來像這樣的對象:

const o: A = {
    id: 'foo',
    key1: 123,
    key2: 456
}

idstring類型的已知且必需的屬性。 其他鍵是動態的並且是數字。

如何在打字稿中定義它?

我已經試過了:

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

這是因為你定義了[key: string]: number和 type 參數是 main。 因此每個密鑰標識符必須具有數字類型(並且 ID 用於智能感知)。 要解決它,您必須這樣做:

type A = {
    id: string;
    [key: string]: number | string
};
var a: A = {
    id: "foo",
    key1: 123,
    key2: "bar" // this is also valid
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM