typescript里有像Swift中extension那种功能吗
是的,TypeScript中也有类似Swift中extension的功能。在TypeScript中,我们可以使用接口扩展类的功能,并且还可以使用命名空间和模块来扩展类。下面是一些示例:
- 使用接口来扩展类的功能:
class MyClass {
name: string;
constructor(name: string) {
this.name = name;
}
}
interface Printable {
print(): void;
}
const printableClass: Printable & typeof MyClass = class extends MyClass implements Printable {
print() {
console.log(`Printing ${this.name}`);
}
};
const instance = new printableClass("Hello");
instance.print(); // Output: Printing Hello
- 使用命名空间来扩展类的功能:
class MyClass {
name: string;
constructor(name: string) {
this.name = name;
}
}
namespace MyClassExtensions {
export function print(this: MyClass) {
console.log(`Printing ${this.name}`);
}
}
const instance = new MyClass("Hello");
MyClassExtensions.print.call(instance); // Output: Printing Hello
- 使用模块来扩展类的功能:
// printer.ts
export function print(this: MyClass) {
console.log(`Printing ${this.name}`);
}
// main.ts
import { print } from "./printer";
class MyClass {
name: string;
constructor(name: string) {
this.name = name;
}
}
MyClass.prototype.print = print;
const instance = new MyClass("Hello");
instance.print(); // Output: Printing Hello
这些都是在TypeScript中扩展类功能的常见方法,类似于Swift中的extension
原文地址: https://www.cveoy.top/t/topic/ihBV 著作权归作者所有。请勿转载和采集!