繁体   English   中英

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

[英]How to declare a "Record" type with partial of specific keys in typescript?

现在,我得到了这个:

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

我想像这样声明一个“记录”类型:

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

嗯,它有效,但是......? 不是很聪明。

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

您可以使用映射类型(类似于Record实现)并指定每个键是可选的:

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

操场

这现在也有效,而且更好:

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

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM