【问题标题】:Typescript access extended Class variables打字稿访问扩展类变量
【发布时间】:2020-12-14 00:36:35
【问题描述】:

我的代码

我有一个“Item”类,它由其他具有自己变量的类扩展,如下所示:

class Item {
  name: string
  symbol: string
  constructor(n: string, s: string){
    this.name = n
    this.symbol = s
  }
}

class Food extends Item {
  type: string
  constructor(n: string, s: string, t: string){
    super(n, s)
    this.type = t
  }
}

class Jewelry extends Item {
  value: number
  constructor(n: string, s: string, v: number){
    super(n, s)
    this.value = v
  }
}

我是这样初始化的:

let items: Array<Food | Jewelry> = []

items.push(new Food('Carrot', 'C', 'Vegetable'))
items.push(new Jewelry('Necklace', 'N', 100))

问题:

现在当我输入 items[0].type 时,编辑器不识别子类“food”特定变量“type”,而只识别父变量“name”和“symbol”。当然与子类“珠宝”相同。

它抛出了这个错误:

Property 'type' does not exist on type 'Food | Jewelry'.
  Property 'type' does not exist on type 'Jewelry'.ts(2339)

如果我像这样隐式设置索引,它会按预期工作:

items[0] = new Food('Carrot', 'C', 'Vegetable')

items[0].type // => 'Vegetable'

即使通过“push()”方法添加对象,我也可以访问子类变量吗?

感谢您的帮助!

干杯

西蒙

【问题讨论】:

    标签: typescript class variables autocomplete extends


    【解决方案1】:

    问题是编译器不知道哪个对象属于数组中的哪个类型。它不知道items[0]Fooditems[1]Jewelry。它只知道在某种程度上都是Items,所以你可以安全地使用item[x].name,因为这是唯一的公共属性。

    但是,您可以稍微支持编译器。例如,通过检查对象属于哪个类,然后使用该额外的类型安全性。

    在下面的示例中,我使用 instanceof 来实现这一点,并且编译器现在不会抱怨访问 type 以获取 Food 对象和 value 以获取 Jewelry 对象:

    class Item {
      name: string
      symbol: string
      constructor(n: string, s: string){
        this.name = n
        this.symbol = s
      }
    }
    
    class Food extends Item {
      type: string
      constructor(n: string, s: string, t: string){
        super(n, s)
        this.type = t
      }
    }
    
    class Jewelry extends Item {
      value: number
      constructor(n: string, s: string, v: number){
        super(n, s)
        this.value = v
      }
    }
    
    let items: Array<Food | Jewelry> = []
    
    items.push(new Food('Carrot', 'C', 'Vegetable'))
    items.push(new Jewelry('Necklace', 'N', 100))
    
    for (const item of items) {
        if (item instanceof Food) {
            console.log(item.type);
        } else if (item instanceof Jewelry) {
            console.log(item.value);
        }
    }
    

    【讨论】:

    • 我明白了。非常感谢,会听取您的建议并检查一下!西蒙
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2013-04-12
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多