打字稿索引签名任何 - 只适用于`any`?

时间:2017-12-30 10:12:25

标签: javascript typescript

我有一个界面和一个类:

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 []; '一个号码;   }'不能赋值为'State'。物业'arr'是   与索引签名不兼容。       类型'undefined []'不能分配给'number'类型。

问题:

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

1 个答案:

答案 0 :(得分:1)

以下界面:

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

在没有创建对象的情况下给出了以下错误:

  

财产' 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[];没有错误。