财产';加载';类型TypeScript上不存在?

财产';加载';类型TypeScript上不存在?,typescript,Typescript,我有两种类型在构造函数中联合。我不知道我会得到什么具体的实现 type TreeLayerActions = { load(): void; } type TreeMapActions = { make(): void; } class A { constructor(private tree: TreeLayerActions | TreeMapActions) { } load() { this.tree.load(); } make(

我有两种类型在构造函数中联合。我不知道我会得到什么具体的实现

type TreeLayerActions = {
  load(): void;
}

type TreeMapActions = {
  make(): void;
}

class A {
  constructor(private tree: TreeLayerActions | TreeMapActions) {
     
  }

  load() {
    this.tree.load();
  }

  make() {
    this.tree.make();
  }
}
为什么会出现此错误:

Property 'load' does not exist on type 'TreeLayerActions | TreeMapActions'.
  Property 'load' does not exist on type 'TreeMapActions'

有两种方法可以正确区分工会:

正如前面所说,您可以添加一个可以检查的文本字段

type TreeLayerActions = {
    type: "layer";
    load(): void;
}

type TreeMapActions = {
    type: "map";
    make(): void;
}

function doSomethingWithUnion(x: TreeLayerActions | TreeMapActions) {
    switch (x.type) {
    case "map":
        x.make()
        return
    case "layer":
        x.load()
        return
    }
}
或者,您可以自己制作:


有两种方法可以正确区分工会:

正如前面所说,您可以添加一个可以检查的文本字段

type TreeLayerActions = {
    type: "layer";
    load(): void;
}

type TreeMapActions = {
    type: "map";
    make(): void;
}

function doSomethingWithUnion(x: TreeLayerActions | TreeMapActions) {
    switch (x.type) {
    case "map":
        x.make()
        return
    case "layer":
        x.load()
        return
    }
}
或者,您可以自己制作:


您可能正在寻找交叉点类型<代码>树结构动作和树结构动作?否则,每次访问属性时,您都必须键入检查
。没有我需要或条件,或
树状结构动作
树状结构
您可能正在寻找交叉点类型<代码>树结构动作和树结构动作?否则每次访问属性时都必须键入检查
。无我需要或条件,或
树操作
树打包