让我们看下面的代码片段:
interface A {
isEmpty(x: any[] | string | object): boolean;
isEmptyObject(x: object): boolean;
}
const a: A = <A>{};
a.isEmptyObject({});
a.isEmptyObject({a: 1});
a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});
当我尝试编译它时,它会崩溃并出现以下错误信息:
a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.
当联合类型(
string | object | any[]
)包含类型object
时,为什么它可以工作(使用{a:1}
的isEmptyObject
调用是可以的)?主要问题:这是TypeScript的bug吗?还是应该如何编写输入可能是任何值或字符串或对象的数组(但不是任何原始类型,我不想要
any
或Object
)?使用TypeScript 2.3.4进行测试。
x
中的任何字段。 - monnef