类型兼容依据。。。
来源:3-14 类 - 公共,私有与受保护修饰符+ readonly 修饰符

旋涡鸣人_
2019-05-29
Property ‘move’ is missing in type ‘Employee’ but required in type ‘Animal’.ts(2741)
test.ts(89, 3): ‘move’ is declared here.
class Animal {
private name: string
constructor(name: string) {
this.name = name
}
move(distance: number = 0) {
console.log(`$(this.name) moved ${distance}m`)
}
}
class Rhino extends Animal {
constructor() {
super('Rhino')
}
}
class Employee {
private name: string
constructor(name: string) {
this.name = name
}
}
let animal = new Animal('Goat')
let rhino = new Rhino()
let employee = new Employee('Bob')
animal = rhino
animal = employee
也就是说 某个变量具有了某个类型之后 不能轻易改变其类型了吗?
还是要判断类型是否兼容?
父类型 一定兼容子类类型 animal = rhino
子类型不一定兼容父类型 rhino = animal (是不是要做个类型diff啊,有啥原则吗)
animal = employee 这个就提示
Type ‘Employee’ is not assignable to type ‘Animal’.
Types have separate declarations of a private property ‘name’.
理解起来还是很别扭。。
3回答
-
仔细看一下文档,理解一下012019-05-30 -
qq_KniGht丶轮回_0
2020-02-24
报错首先是检查到employee没有move属性,所以是不能赋值给animal的,他们类型不兼容。然后如果你给Employee加上move属性,就会报老师视频里说的错误,两者的name都是各自的私有属性,不是同一个来源的name,也不兼容。
00 -
抓瞎程序猿
2019-05-29
rhino是继承与父类型animal的,name属性是同一个(继承过来的),所以是父类与子类是可以相互赋值的,是兼容的(我的理解)。而employee和animal虽然定义相同,但是他们有各自的name,employee的name和animal的name显然不是同一个name。所以存在兼容问题。
012019-05-30
相似问题