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

问题描述 投票:4回答:1

我有一个接口和一个类:

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'类型。

题:

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

javascript typescript
1个回答
1
投票

以下界面:

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

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

'any []'类型的属性'arr'不能赋予字符串索引类型'number'

这是因为一旦定义了[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[];

© www.soinside.com 2019 - 2024. All rights reserved.