可能我在这里遗漏了一些明显的东西,但是为什么这不起作用?
this.props.entity
绝对是GraphData类型的,并且delta中的属性在GraphData上有效。
const newEntity: GraphData = {...this.props.entity, ...delta } as GraphData;
if(newEntity instanceof GraphData) {
console.log('Yay');
}
即使这不起作用
const newEntity: GraphData = {...this.props.entity } as GraphData;
if(newEntity instanceof GraphData) {
console.log('Yay');
}
newEntity始终是对象类型
答案 0 :(得分:2)
Typescript有一个structural type system。这意味着,如果定义class A { x: number = 1; }
,则对象字面量{x: 1}
的类型为A
,即使它不是像new A()
那样构造。
但是,instanceof
是Javascript,因此它在Typescript as it has in Javascript中具有相同的语义:
instanceof
运算符测试构造函数的prototype
属性是否出现在对象原型链的任何位置。
因此,由于对象文字{x: 1}
在其原型链中没有A.prototype
,因此{x: 1} instanceof A
为假。也就是说,instanceof
不测试对象是否在Typescript中具有特定类型。
答案 1 :(得分:1)
如果要使用GraphData
类的实例,则必须使用new
运算符:
const newEntity = new GraphData(/* ... */);
或者,您可以将GraphData
声明为interface
或type
,但是在运行时将无法使用instanceof
。