TypeScript-函数兼容性
原创
©著作权归作者所有:来自51CTO博客作者一个爱听音乐的程序员的原创作品,请联系作者获取转载授权,否则将追究法律责任
参数个数
let fn1 = (x: number, y: number) => {
};
let fn2 = (x: number) => {
};
fn1 = fn2;
let fn1 = (x: number, y: number) => {
};
let fn2 = (x: number) => {
};
fn2 = fn1;
参数类型
-
可以
将参数类型一样的函数赋值给参数类型一样的函数
let fn1 = (x: number) => {
};
let fn2 = (x: number) => {
};
let fn3 = (x: string) => {
};
fn1 = fn2;
fn2 = fn1;
-
不可以
将参数类型不一样的函数赋值给参数类型不一样的函数, 必须一模一样
let fn1 = (x: number) => {
};
let fn2 = (x: number) => {
};
let fn3 = (x: string) => {
};
fn1 = fn3;
fn3 = fn1;
返回值类型
-
可以
将返回值类型一样的函数赋值给返回值类型一样的函数
let fn1 = (): number => 123;
let fn2 = (): number => 456;
let fn3 = (): string => 'abc';
fn1 = fn2;
fn2 = fn1;
-
不可以
将返回值类型不一样的函数赋值给返回值类型不一样的函数,必须一模一样
let fn1 = (): number => 123;
let fn2 = (): number => 456;
let fn3 = (): string => 'abc';
fn1 = fn3;
fn3 = fn1;
函数双向协变
参数的双向协变
let fn1 = (x: (number | string)) => {
};
let fn2 = (x: number) => {
};
fn1 = fn2;
fn2 = fn1;
返回值双向协变
let fn1 = (x: boolean): (number | string) => x ? 123 : 'abc';
let fn2 = (x: boolean): number => 456;
fn1 = fn2;
let fn1 = (x: boolean): (number | string) => x ? 123 : 'abc';
let fn2 = (x: boolean): number => 456;
fn2 = fn1;
函数重载
function add(x: number, y: number): number;
function add(x: string, y: string): string;
function add(x, y) {
return x + y;
}
function sub(x: number, y: number): number;
function sub(x, y) {
return x - y;
}
function add(x: number, y: number): number;
function add(x: string, y: string): string;
function add(x, y) {
return x + y;
}
function sub(x: number, y: number): number;
function sub(x, y) {
return x - y;
}
let fn = add;
fn = sub;
function add(x: number, y: number): number;
function add(x: string, y: string): string;
function add(x, y) {
return x + y;
}
function sub(x: number, y: number): number;
function sub(x, y) {
return x - y;
}
let fn = sub;
fn = add;