嵌套对象没有进行类型检查

Type checking is not happening for nested object

我正在开发 Angular 应用程序。因为我有一个接口 IAbc:

interface IAbc {
    id: number,
    name: string
}

另一个接口IXyz使用上面的接口如下:

interface IXyz {
    id: number,
    value: string | number | Date | IAbc[];
}

这里,值可以是任何类型的数据,所以我缩小了类型。

我创建了一个新变量:

let someVar: IXyz;

someVar = {
    id: 100,
    value: [
        {
            id: 1,
            name: 'abc'
        },
        {
            id: 2,
            name: 'xyz'
        }
    ]
};

因为值也可以是一个列表,所以我必须使用 forEach 来做一些操作:

someVar.value.forEach((x: IAbc) => console.log('some operation on value, ', x))

但是,我在 forEach 上收到此错误:

Property 'forEach' does not exist on type 'string | number | Date | IAbc[]'.
  Property 'forEach' does not exist on type 'string'.(2339)

我认为这在逻辑上应该可行。打字稿有问题吗?

我创建了一个 playground link,我在其中复制了这个。

让我知道你的想法。谢谢!


P.S.: 我知道我可以在那里使用 any 并且它会顺利运行,但是 any 的使用已被应用程序的 linting 禁用。

要消除错误,您可以使用类型保护。

function isArray(value: string | number | Date | IAbc[]): value is IAbc[] {
  return (value as IAbc[]).forEach !== undefined;
}

if( isArray(someVar.value) ) {
    someVar.value.forEach((x: IAbc) => console.log('some operation on value, ', x))
}

您可以在您的 playground 的更新版本中看到它工作 here

你需要一个类型转换来告诉编译器这确实是一个数组

(someVar.value as IAbc[]).forEach((x: IAbc) => console.log('some operation on value, ', x))