Typescript联合类型-Array forEach错误

时间:2018-11-27 19:25:51

标签: typescript union-types

如何解决此打字稿错误

export interface State {
    ids: number[] | string[];
}
const state: State = {ids: []};
state.ids.forEach(s => { }); // error here!!!

一种方法是,我将IDs分别放入一个变量中,然后将其强制转换然后遍历该变量

const ids = <string[]>state.ids;
ids.forEach(s => { });

但这看起来不是很整洁。有什么办法可以在同一行中投射和循环播放? 像

state.ids.forEach<string[]>(s => { }) // not working

1 个答案:

答案 0 :(得分:0)

您会发现this GitHub thread 很有趣。该问题与无法推断数组联合(在您的情况下为 number[]string[])之间的通用类型有关。但是,从 v3.3enter link description here 开始,可以在数组联合上调用 forEach,除非 --noImplicitAny 标志打开(因为回调的第一个参数将隐式输入为 { {1}})。

所以现在您的问题可以在没有 any 强制转换的情况下解决,但仍然需要在回调中进行显式类型注释:

as

这更符合您的 type union = number[] | string[]; const i : union = []; i.forEach((elem: number | string) => { //ok, do something }); 类型,因为显式强制转换并不安全。拥有数组的联合通常表明泛型会更合适。以下是如何更改接口以保留类型检查并完全避免最初的问题:

State

此外,请参阅 this Q&A 中有关应用于 export interface State<I extends number | string>{ ids: I[]; } const state: State<string> = {ids: [1,2,3]}; //error state.ids.forEach(s => { }); //ok if above is fixed 方法的相同问题。