打字稿索引签名 any - 仅适用于“any”



我有一个接口和一个类:

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:键入"{ arr: undefined[];"a":数字; }' 不能分配给类型"状态"。 属性"arr"是 与索引签名不兼容。 类型"undefined[]"不能分配给类型"数字"。

问题:

为什么?
我不明白这个限制背后的逻辑。我该怎么做才能解决它?

以下界面:

export interface State {
    arr : any[];
    [key: string]: number
}

给我以下错误,甚至没有创建对象:

类型

为"any[]"的属性"arr"不可分配给字符串索引类型 "数字">

这是因为一旦你定义了[key: string]: number,TypeScript 认为所有属性都应该是映射到数字的字符串。所以你不能有一个数组,除非你这样做:

export interface State {
    [key: string]: number | any[]
}

请注意,以下界面工作的原因:

export interface State {
    arr : any[];
    [key: string]: any
}

[key: string]: any告诉 TypeScript "将字符串映射到任何内容",换句话说,"关闭每个字符串属性的类型检查"。这就是为什么您可以毫无错误地拥有arr : any[];的原因。

最新更新