现在,我得到了这个:
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)
呃,它有效,但是……?不太聪明。
(顺便说一句,请原谅我糟糕的英语,谢谢)
A-S*_*A-S 16
现在这也可以工作,并且更好、更易读:
type T_Platforms = Partial<Record<T_PlatformKey, T_PlatformInfo>>;
Run Code Online (Sandbox Code Playgroud)
Ale*_* L. 11
您可以使用映射类型(类似于Record实现)并指定每个键都是可选的:
type T_Platforms = { [Key in T_PlatformKey]?: T_PlatformInfo }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6736 次 |
| 最近记录: |