当一个类型Y可以被赋值给另一个类型X时,就可以说类型X兼容类型Y。广泛存在与接口、函数和类中 当原类型必须具备目标类型的必要属性时就可以赋值
ts//类型兼容性
interface user1 {
name:string
}
interface user2 {
name:string
age:number
sex:number
}
let a:user1 = {name:"xiao"}
let b:user2 = {name:"ming",age:18,sex:0}
a = b //当原类型必须具备目标类型的必要属性时就可以赋值
b= // error
原函数参数个数小于目标函数参数个数(成员少的兼容成员多的)
ts// 简单情况 两个函数参数都是固定参数
type myFn=(a:number,b:number)=>void
function num(myFn:myFn){
return myFn
}
// 原函数参数个数小于目标函数参数个数
let myFn1=(a:number)=>{}
num(myFn1)
let myFn2=(a:number,b:number,c:number)=>{}
//num(myFn2)//error 类型“(a: number, b: number, c: number) => void”的参数不能赋给类型“myFn”的参数。
.......
//复杂情况
//1. 参数个数
//函数可选参数和剩余参数
let a = (x:number,y:number)=>{} //含有固定参数
let b = (x?:number,y?:number)=>{} // 含有可选参数
let c = (x:number,...y:number[])=>{} //含有剩余参数
//固定参数可以兼容可选参数和剩余参数
a = b
a = c
//可选参数不兼容固定参数和剩余参数 启用tsconfig.json中strictFunctionTypes:false,则不会报错可以兼容
b = a
b = c
//剩余参数可以兼容固定参数和可选参数
c = a
c = b
若两个函数的参数类型都是对象,参数多的兼容参数少的 两个函数相互赋值的情况称之为双向协变
tsinterface point3D {
x: number;
y: number;
z: number;
}
interface point2D {
x: number;
y: number;
}
let p3d = (point: point3D) => {};
let p2d = (point: point2D) => {};
p3d = p2d;
// p2d = p3d;//error
目标函数的返回值类型与原函数的返回值类型相同或为其子类型,成员少的兼容成员多的
tslet a = () => ({ x: 1, y: 2 });
let b = () => ({ x: 1, y: 2, z: 3 });
a = b
b = a//error
......
function myfn(x: number, y: number): number;
function myfn(x: number, y: number): string;
// function myfn(x: any, y: any): any {}
// function myfn(x: any, y: any,z:any): any {} //error 重载列表的目标函数参数小于原函数的参数报错,应该大于原函数参数才兼容
function myfn(x: any, y: any,){} //返回值类型必须与重载列表中目标函数的类型相同或为其子类型
### 枚举类型兼容性
//枚举类型
enum info1 {name}
enum info2 {age,sex}
enum info3 {active="move"}
let man:info1.name = 3
let human:number = info2.age
let manActive:string = info3.active
// let people:info1.name = info2.age //error
tsclass aBox {
constructor() {
}
name: string = "123"
age: number = 18
}
class bBox {
constructor() {
}
name: string = "123"
age: number = 18
}
let a = new aBox()
let b = new bBox()
a = b
b = a
ts
class aBox {
constructor() {
}
name: string = "123"
age: number = 18
}
class bBox {
constructor() {
}
name: string = "123"
}
let a = new aBox()
let b = new bBox()
a = b//error
b = a
tsclass aBox {
constructor() {
}
private name: string = "123"
}
class bBox {
constructor() {
}
name: string = "123"
}
let a = new aBox()
let b = new bBox()
a = b
b = a
tsclass aBox {
constructor() {
}
private name: string = "123"
}
class bBox extends aBox{}
let a = new aBox()
let b = new bBox()
a = b
b = a
当泛型T被使用时无法兼容
tsinterface name<T>{
value:T
}
let obj1:name<number>={value:18}
let obj2:name<string>={value:"小明"}
obj1 = obj2//error
obj2 = obj1//error
可以相互兼容
tslet getname=<T>(x:T):T =>{return x}
let getage=<U>(x:U):U =>{return x}
getage = getname
当一个类型Y可以赋值给类型X时,则称之为类型X可以兼容类型Y 结构之间兼容:成员少的可以兼容成员多的 函数之间兼容:参数多的可以兼容参数少的
本文作者:RKLS
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!