문 병합
类型合并
두 개와 같은 문장, 후자 는 두 개의 특성을 가지고 编译器
있음을 나타냅니다 . 뿐만 아니라 여러 개를 결합할 수 있습니다 .合并
分开
名称
合并
声明
声明
声明
两个
인터페이스 병합
1. 1. interface
의 비함수 멤버는 고유해야 합니다. 둘 다 하나 를 interface
선언 하면 오류 메시지가 표시됩니다.名称相同但类型不同
非函数成员
编译器
interface Box {
height: number;
}
interface Box {
height: string;
}
复制代码
2. 의 경우 函数成员
각각의 멤버는 相同名称
으로 표시 相同名称函数的重载
되지만 2개가 interface
있는 경우 第二个有更高的优先
클래스는 이전 클래스를 재정의합니다.
interface Cloner {
clone(animal: Animal): Animal;
}
interface Cloner {
clone(animal: Sheep): Sheep;
}
interface Cloner {
clone(animal: Dog): Dog;
clone(animal: Cat): Cat;
}
// 最终的排序是
interface Cloner {
clone(animal: Dog): Dog;
clone(animal: Cat): Cat;
clone(animal: Sheep): Sheep;
clone(animal: Animal): Animal;
}
复制代码
물론 이 규칙에는 예외가 있습니다. 함수의 매개변수 유형이 单字面量类型
(단일 문자열 리터럴 유형)인 경우 다음과 같이 优先级排序
배치 됩니다 声明顶部
.
interface Document {
createElement(tagName: any): Element;
}
interface Document {
createElement(tagName: 'div'): HTMLDivElement;
createElement(tagName: 'span'): HTMLSpanElement;
}
interface Document {
createElement(tagName: string): HTMLElement;
createElement(tagName: 'canvas'): HTMLCanvasElement;
}
// 字面量根据冒泡排序并放在了声明顶部
interface Document {
createElement(tagName: 'canvas'): HTMLCanvasElement;
createElement(tagName: 'div'): HTMLDivElement;
createElement(tagName: 'span'): HTMLSpanElement;
createElement(tagName: string): HTMLElement;
createElement(tagName: any): Element;
}
复制代码
네임스페이스 병합
- 같은 이름의 두 개를 병합 하면 첫 번째 이름
namespace
에 두 번째 항목이 더 추가namespace
됩니다 .导出的成员
namespace
namespace Animals {
export class Zebra {}
}
namespace Animals {
export interface Legged {
numberOfLegs: number;
}
export class Dog {}
}
// 合并到了第一个
namespace Animals {
export interface Legged {
numberOfLegs: number;
}
export class Zebra {}
export class Dog {}
}
复制代码
- 병합이 발생 하면
namespace
병합된 항목에namesapce
액세스할 수 없습니다未导出的成员
.
namespace Animal {
const haveMuscles = true;
export function animalsHaveMuscles() {
return haveMuscles;
}
}
namespace Animal {
export function doAnimalsHaveMuscles() {
return haveMuscles; // Error, because haveMuscles is not accessible here
}
}
复制代码
접근할 수 없는 것을 볼 수 있으며
haveMuscles
동시에 실행시 오류가 보고되는 것을 볼 수 있으며 컴파일된 예제와 함께 볼 수 있습니다.
네임스페이스 및 클래스, 열거형, 함수 병합
- 병합
namespace
과 마찬가지로 내보낸 합계 는 다음에서class
액세스할 수 있습니다 .namespace
类型
值
class Album {
label: Album.AlbumLabel;
}
namespace Album {
export class AlbumLabel {}
}
复制代码
namespace
function
merge는 다음과 같은 메소드에 속성을 추가할 수 있습니다javascript
.
function buildLabel(name: string): string {
return buildLabel.prefix + name + buildLabel.suffix;
}
namespace buildLabel {
export const suffix = '';
export const prefix = 'Hello, ';
}
console.log(buildLabel('Sam Smith'));
复制代码
컴파일된 코드를 보면 buildLabel
속성이 다음 위치에 직접 추가된 것을 볼 수 있습니다.
namespace
병합 이enum
발생하면namespace
확장될 수 있습니다.enum
enum Color {
red = 1,
green = 2,
blue = 4,
}
namespace Color {
export function mixColor(colorName: string) {
if (colorName == 'yellow') {
return Color.red + Color.green;
} else if (colorName == 'white') {
return Color.red + Color.green + Color.blue;
} else if (colorName == 'magenta') {
return Color.red + Color.blue;
} else if (colorName == 'cyan') {
return Color.green + Color.blue;
}
}
}
复制代码
컴파일 후 다음을 볼 수 있습니다.
클래스 간 병합은 허용되지 않지만 유사한 기능을 모방해야 하는 경우 Typscripts에서 Mixins를 참조할 수 있습니다.
모듈 확장
이들 간의 병합은 지원되지 않지만 필요한 메서드를 Module
가져온 다음 사용하여 구현할 수 있습니다 .扩展
更改
// observable.ts
export class Observable<T> {
// ... implementation left as an exercise for the reader ...
}
// map.ts
import { Observable } from "./observable";
Observable.prototype.map = function (f) {
// ... another exercise for the reader
};
复制代码
그러나 이런 식으로 컴파일러는 좋은 힌트를 제공하지 않으므로 확장 module
선언이 필요합니다.
// observable.ts
export class Observable<T> {
// ... implementation left as an exercise for the reader ...
}
// map.ts
import { Observable } from "./observable";
declare module "./observable" {
interface Observable<T> {
map<U>(f: (x: T) => U): Observable<U>;
}
}
// 扩展声明
Observable.prototype.map = function (f) {
// ... another exercise for the reader
};
// consumer.ts
import { Observable } from "./observable";
import "./map";
let o: Observable<number>;
o.map((x) => x.toFixed());
复制代码
글로벌 확장
全局声明中
모듈에 있는 경우 여기에서 확장 할 수도 있습니다 .
// observable.ts
export class Observable<T> {
// ... still no implementation ...
}
// 在这里扩展
declare global {
interface Array<T> {
toObservable(): Observable<T>;
}
}
Array.prototype.toObservable = function () {
// ...
};
复制代码
참조 선언 병합