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;
|
请发表评论