小编Rai*_*ode的帖子

如何在打字稿中声明带有部分特定键的“记录”类型?

现在,我得到了这个:

type T_PlatformKey= 'pf1' | 'pf2' | 'pf3'
type T_PlatformInfo = {
    key: T_PlatformKey
    name: string
    [k: string]: any
}
Run Code Online (Sandbox Code Playgroud)

我想声明一个“记录”类型,如下所示:

type T_platforms = Record<T_PlatformKey, T_PlatformInfo>

const platforms: T_Platforms = {} // here is the problem
Run Code Online (Sandbox Code Playgroud)

如果我不声明所有属性:

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

我尝试过像这样的其他方式:

interface I_Platforms {
    pf1: T_PlatformInfo
    pf2: T_PlatformInfo
    pf3: T_PlatformInfo
}
const platforms: Partial<I_Platforms> = {} // it works
Run Code Online (Sandbox Code Playgroud)

呃,它有效,但是……?不太聪明。

(顺便说一句,请原谅我糟糕的英语,谢谢)

typescript

9
推荐指数
2
解决办法
6736
查看次数

标签 统计

typescript ×1