如何在Typescript中使用扩展原型添加文件 [英] How to add file with extending prototype in Typescript

查看:666
本文介绍了如何在Typescript中使用扩展原型添加文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose i want to extend String.prototype, so i have this in ext/string.ts for example:

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'时,它将失败,并显示以下错误:

When i do import * as string from 'ext/string.ts' it fails with this error:

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

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

这被认为是行为,我没有写export. 但是我如何告诉Typescript我要扩展String.prototype呢?

and this is supposed behavior , i didn't write export. But how do i tell to Typescript that i want to extend String.prototype then?

推荐答案

您只需要运行文件而无需导入任何内容.您可以使用以下代码来做到这一点:

You just need to run the file without importing anything. You can do that with this code:

import "./ext/string";


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


However, if your string.ts file contains any import statements then you will need to take out the interface and put it in a definition file (.d.ts). You need to do this with external modules so that the compiler knows it needs to be merged with the String interface in the global scope. For example:

// 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

这篇关于如何在Typescript中使用扩展原型添加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆