Statement merger
If the same name defines two functions, interface or class, they will be merged into a Type:
Merge function
Before learning too overloaded, we can use the overloaded define multiple types of functions:
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}
The combined interface
Interface properties when the merger will be merged into a simple interface:
interface Alarm {
price: number;
}
interface Alarm {
weight: number;
}
It is equivalent to:
interface Alarm {
price: number;
weight: number;
}
Note that the type of merger of the property must be unique :
interface Alarm {
price: number;
}
interface Alarm {
price: number; // 虽然重复了,但是类型都是 `number`,所以不会报错
weight: number;
}
interface Alarm {
price: number;
}
interface Alarm {
price: string; // 类型不一致,会报错
weight: number;
}
// index.ts(5,3): error TS2403: Subsequent variable declarations must have the same type. Variable 'price' must be of type 'number', but here has type 'string'.
The combined method interface, combined with the function as:
interface Alarm {
price: number;
alert(s: string): string;
}
interface Alarm {
weight: number;
alert(s: string, n: number): string;
}
It is equivalent to:
interface Alarm {
price: number;
weight: number;
alert(s: string): string;
alert(s: string, n: number): string;
}
The combined class
Merger and merger rules consistent interface class.
- This article refers to xcatliu