简体   繁体   English

属性'prop'在类型'A |中不存在。 B'

[英]Property 'prop' does not exist on type 'A | B'

I am fetching data from an url and if a certain condition is met, the data is loaded inside a type B or its superclass A. When the data is loaded in B, typescript does not recognise its properties. 我正在从url中获取数据,如果满足特定条件,则将数据加载到类型B或它的超类A中。当将数据加载到B中时,打字稿无法识别其属性。 I get the following error with the code below: 我收到以下代码以下错误:

Property 'doB' does not exist on type 'A' 类型“ A”上不存在属性“ doB”

class A {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    doA() {
        return "Hello, " + this.greeting;
    }
}
class B  extends A{
    greeting: string;
    constructor(message: string) {
        super(message)
        this.greeting = message;
    }
    doB() {
        return "Hello, " + this.greeting;
    }
}

let greeter: A|B  = new B("world");
greeter.doB()

When you define a type as A|B , this is a Union Type in TypeScript. 当您将类型定义为A|B ,这是TypeScript中的联合类型

When using a union type, typescript by default would only allow you to use the properties that are present on both the types. 使用联合类型时,默认情况下,打字稿仅允许您使用两种类型上都存在的属性。 In this case, an example of that would be doA . 在这种情况下, doA就是一个例子。

But if we can only access those, then the type won't make much sense. 但是,如果我们只能访问那些类型,那么类型就没有多大意义。 To access a property that is only present on one of the instances, all you have to do is to make sure it has the correct instance type or Type Gaurd. 要访问仅在其中一个实例上存在的属性,您要做的就是确保其具有正确的实例类型或Type Gaurd。 In this case, that can be done with: 在这种情况下,可以通过以下方式完成:

let greeter: A|B  = new B("world");
if(greeter instanceof B) {
    // Do just B things
} else if(greeter instanceof A) {
   // Do only A things
}

The error makes sense. 该错误是有道理的。 How can you call doB with certainty if the defined type for var greeter is A or B (and A does not have member doB() defined)? 如果var greeter的定义类型是A B (并且A没有定义成员doB() ),如何确定地调用doB

greeter is of type either A or BI am assuming. 迎宾者的类型是A或BI。 So why typescript does not allow me to call a method of B ? 那么为什么打字稿不允许我调用B的方法?

Because greeter could also be an instance of A which would break type safety if the transpiler did allow it. 因为greeter也可以是A的实例, 如果编译器允许的 ,它将破坏类型安全性。

Having a type of A | B A | B A | B only allows you do access properties that exist on both. A | B仅允许您访问两个目录中都存在的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM