-
Notifications
You must be signed in to change notification settings - Fork 508
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Q692】什么是协变与逆变 #713
Comments
|
TypeScript 逆变和协变
一些概念Subtyping 子类型在编程语言理论中,子类型是一种类型多态的形式,这种类型可以替换其超类型(supertype)。如果 S 是 T 的子类型,一般表示为 S <: T,意思是在任何类型为 T 的地方都可以安全的使用 S。 type T = number
type S = T | string
type Fn = (arg: T) => void
let fn: Fn = (arg: S) => {} 上面的代码我们定义了 T 和 S 类型,然后定义了一个 参数为 T 返回值为 any 的函数类型 Fn, 但是在具体的赋值的时候我们将 args 变为 S,程序是可以正常运行的。 协变与逆变
TypeScript实现考虑如下类型 dinterface Animal {
name: string
}
interface Dog extends Animal {
// 摇尾巴
waggingTail(): void
}
interface Corgi extends Dog {
canWagging: false
} 代码中我们定义了三个类型,他们之间的子集关系为 Corgi <: Dog <: Animal。 // 协变
type AnimalList = Array<Animal>
type DogList = Array<Dog>
let animalArr: AnimalList = [];
let dogArr: DogList = [];
// ✅ DogList 为 AnimalList 子集
animalArr = dogArr; 我们再考虑一种特殊情况 type Fn1 = (arg: Dog) => Dog Fn1 类型的子类型是什么呢?
参考 |
dinterface Animal -> interface |
No description provided.
The text was updated successfully, but these errors were encountered: