Skip to content
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

协变、逆变、双向协变和不变的理解? #146

Open
GGXXMM opened this issue Apr 15, 2023 · 0 comments
Open

协变、逆变、双向协变和不变的理解? #146

GGXXMM opened this issue Apr 15, 2023 · 0 comments

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Apr 15, 2023

协变:X = Y

Y类型是X类型的子类,Y类型可以赋值X类型,即为协变。

interface X { name: string; age: number; } 
interface Y { name: string; age: number; hobbies: string[] }
let x: X = { name: 'xiaoming', age: 16 }
let y: Y = { name: 'xiaohong', age: 18, hobbies: ['eat'] }
x = y

逆变:printY = printX

printY 的参数 Y 是 printX 参数 X 子类,函数printY调用只用到父类型的属性和方法,类型是安全。

let printY: (y: Y) => void
printY = (y) => { console.log(y.hobbies) }
let printX: (x: X) => { console.log(x.name) }

printY = printX// 支持
printX = printY// 报错

双向协变:printX = printY;printY = printX

子类型可以赋值付类型,父类型也可以赋值子类型,既协变又逆变,叫做“双向协变”。在ts2.x之前支持这种赋值;之后ts加了一个编译选项 strictFunctionTypes,设置为 true 时只支持逆变,设置为 false 则支持双向协变。

不变

非父子类型之间不会发生型变,只要类型不一样就会报错。

@GGXXMM GGXXMM changed the title 逆变、协变、双向协变和不变的理解? 协变、逆变、双向协变和不变的理解? Jul 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant