網站搜尋

如何在 TypeScript 中聲明具有特定鍵部分的 "Record" 類型?


現在,我得到這個:

type T_PlatformKey= 'pf1' | 'pf2' | 'pf3'
type T_PlatformInfo = {
    key: T_PlatformKey
    name: string
    [k: string]: any
}

我想要宣告一個像這樣的「Record」類型:

type T_platforms = Record<T_PlatformKey, T_PlatformInfo>

const platforms: T_Platforms = {} // here is the problem

如果我沒有聲明所有屬性:

Type '{}' is missing the following properties from type 'Record<T_PlatformKey, T_PlatformInfo>': pf1, pf2, pf3 ts(2739)

我嘗試過像這樣的其他方法:

interface I_Platforms {
    pf1: T_PlatformInfo
    pf2: T_PlatformInfo
    pf3: T_PlatformInfo
}
const platforms: Partial<I_Platforms> = {} // it works

呃,它可以用,但…?不是很聰明。

(順便說一下,請原諒我糟糕的英文,謝謝)

答案#1

這現在也可以使用,而且更漂亮、更易讀:

type T_Platforms = Partial<Record<T_PlatformKey, T_PlatformInfo>>;

遊樂場

答案#2

您可以使用映射類型(類似於 Record 的實現)並指定每個鍵是可選的:

type T_Platforms = { [Key in T_PlatformKey]?: T_PlatformInfo }

遊樂場