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

lay*_*out 2 javascript typescript typescript1.8

假设我想扩展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);
};
Run Code Online (Sandbox Code Playgroud)

当我这样做import * as string from 'ext/string.ts'失败时出现此错误:

错误TS2306:文件'\ text/string.ts'不是模块

这是假设的行为,我没有写出口.但是我怎么告诉Typescript我想扩展String.prototype呢?

Dav*_*ret 7

您只需要在不导入任何内容的情况下运行该文件.您可以使用以下代码执行此操作:

import "./ext/string";
Run Code Online (Sandbox Code Playgroud)

但是,如果您的string.ts文件包含任何import语句,则需要取出接口并将其放在定义文件(.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
Run Code Online (Sandbox Code Playgroud)