如何在 Typescript 中添加带有扩展原型的文件

How to add file with extending prototype in Typescript

假设我想扩展 String.prototype,所以我在 ext/string.ts 中有这个,例如:

interface String {
    contains(sub: string): boolean;
}

String.prototype.contains = function (sub:string):boolean {
    if (sub === "") {
        return false;
    }
    return (this.indexOf(sub) !== -1);
};

当我执行 import * as string from 'ext/string.ts' 时失败并出现此错误:

error TS2306: File 'ext/string.ts' is not a module

这是假定的行为,我没有写导出。 但是我该如何告诉 Typescript 我想扩展 String.prototype 呢?

您只需要 运行 文件,无需导入任何内容。您可以使用此代码执行此操作:

import "./ext/string";

但是,如果您的 string.ts 文件包含任何导入语句,那么您将需要取出接口并将其放入定义文件 (.d.ts)。您需要对外部模块执行此操作,以便编译器知道它需要与全局范围内的 String 接口合并。例如:

// customTypings/string.d.ts
interface String {
    contains(sub: string): boolean;
}

// ext/string.ts
String.prototype.contains = function(sub:string): boolean {
    if (sub === "") {
        return false;
    }
    return (this.indexOf(sub) !== -1);
};

// main.ts
import "./ext/string";

"some string".contains("t"); // true