Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Typescript中使用扩展原型添加文件_Javascript_Typescript_Typescript1.8 - Fatal编程技术网

Javascript 如何在Typescript中使用扩展原型添加文件

Javascript 如何在Typescript中使用扩展原型添加文件,javascript,typescript,typescript1.8,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) !=

假设我想扩展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);
};
// 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
当我从“ext/string.ts”执行
import*作为字符串时,
失败,出现以下错误:

错误TS2306:文件“ext/string.ts”不是模块

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

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

import "./ext/string";

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

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

String.prototype.contains = function (sub:string):boolean {
    if (sub === "") {
        return false;
    }
    return (this.indexOf(sub) !== -1);
};
// 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

老实说,你真的应该考虑不扩展像这样的内置类型。当未来的某个ES版本推出自己的
包含
的本机实现时,您的代码将覆盖该实现,并且可能比本机代码慢。看见