【发布时间】: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