必看 协变与逆变 | 深入理解 TypeScript
class Animal {
a !: string
}
class Dog extends Animal {
b !: string
}
class Greyhound extends Dog {
c !: string
}
class GermanShepherd extends Dog {
d !: string
}
function f (arg1: (arg1: Dog) => Dog): string {
return ''
}
// 1、Greyhound → Greyhound
function f1(farg1: Greyhound): Greyhound {
return {
a: '',
b: '',
c: ''
}
}
// 2、Greyhound → Animal
function f2(farg1: Greyhound): Animal {
return {
a: '',
}
}
// 3、Animal → Animal
function f3(farg1: Animal): Animal {
return {
a: '',
}
}
// 4、Animal → Greyhound
function f4(farg1: Animal): Greyhound {
return {
a: '',
b: '',
c: ''
}
}
f(f4)
TypeScript: Playground
网友评论