【发布时间】:2018-06-10 12:05:30
【问题描述】:
我有一个接口和一个类:
export interface State {
arr : any[];
}
export const INITIAL_STATE: State = {
arr: []
};
这会编译。
现在我将界面更改为:
export interface State {
arr : any[];
[key: string]: any
}
而类是这样的:
export const INITIAL_STATE: State = {
arr: [] ,
'a':2
};
- 仍然编译。
但是现在 - 如果我想更严格:[key: string]: any ---> [key: string]: number:
换句话说:
export interface State {
arr : any[];
[key: string]: number
}
export const INITIAL_STATE: State = {
arr: [] ,
'a':2
};
我得到一个错误:
错误:(7, 14) TS2322: Type '{ arr: undefined[]; '一个号码; }' 不可分配给类型 'State'。属性“arr”是 与索引签名不兼容。 类型 'undefined[]' 不能分配给类型 'number'。
问题:
为什么会这样?
我不明白这个限制背后的逻辑。
我能做些什么来解决它?
【问题讨论】:
-
一旦你有一个字符串或数字索引签名,所有显式成员也必须符合那个索引签名。在你的情况下,一切都必须是一个字符串。这是为了提供安全性,但您可以使用
[key: string]: string | number;支持数字和字符串索引 -
@Kokodoko 说实话 - 我不明白而且我没有看到任何潜在的问题。您介意发布答案吗?
-
我打赌那是因为 js 对象要么没有动态属性,要么被用作 hashmap。
标签: javascript typescript