传播后打字稿类型丢失

时间:2020-02-12 14:24:07

标签: typescript

可能我在这里遗漏了一些明显的东西,但是为什么这不起作用?

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始终是对象类型

2 个答案:

答案 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声明为interfacetype,但是在运行时将无法使用instanceof