We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
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 的参数 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// 报错
子类型可以赋值付类型,父类型也可以赋值子类型,既协变又逆变,叫做“双向协变”。在ts2.x之前支持这种赋值;之后ts加了一个编译选项 strictFunctionTypes,设置为 true 时只支持逆变,设置为 false 则支持双向协变。
strictFunctionTypes
非父子类型之间不会发生型变,只要类型不一样就会报错。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
协变:X = Y
Y类型是X类型的子类,Y类型可以赋值X类型,即为协变。
逆变:printY = printX
printY 的参数 Y 是 printX 参数 X 子类,函数printY调用只用到父类型的属性和方法,类型是安全。
双向协变:printX = printY;printY = printX
子类型可以赋值付类型,父类型也可以赋值子类型,既协变又逆变,叫做“双向协变”。在ts2.x之前支持这种赋值;之后ts加了一个编译选项
strictFunctionTypes
,设置为 true 时只支持逆变,设置为 false 则支持双向协变。不变
非父子类型之间不会发生型变,只要类型不一样就会报错。
The text was updated successfully, but these errors were encountered: