打字稿中的扩展方法(系统)

时间:2016-04-05 17:17:37

标签: typescript angular prototype typescript1.8

在我的angular2项目中,我正在尝试使用typescript扩展 string 类的原型。 这是我的代码:

interface String 
{
    startsWith(s:string);
    contains(s:string);
    containsOr(s1:string, s2:string);
}

String.prototype.startsWith = function (s:string):boolean {
    return this.indexOf (s) === 0;
}
String.prototype.contains = function (s:string):boolean {
    return this.indexOf(s) > 1;
}
String.prototype.containsOr = function (s1:string, s2:string):boolean {
    return this.indexOf(s1) > 1 || this.indexOf (s2) > 1;
}

使用此代码编译项目(也是Visual Studio Code的内容辅助协助我)但在运行时我得到'包含未定义'。

我做错了什么?

非常感谢

PS:这是我的tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "wwwroot/app/source/"
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "wwwroot",
    "typings/main",
    "typings/main.d.ts"
  ]
}

修改

我注意到导入 index.html 中的 js 文件有效,但我不喜欢这种做法。

<script src="app/source/utils/extensions.js"></script>

2 个答案:

答案 0 :(得分:16)

我能够使用以下模板解决没有TS错误(1.8.9),Angular2(2.0.0-beta.12)错误和工作函数调用的问题:

<强> tsconfig.json

{
  "compilerOptions": {
  "target": "es5",
  "module": "system",
  "moduleResolution": "node",
  "sourceMap": true,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "removeComments": false,
  "noImplicitAny": false
},
"exclude": [
  "node_modules",
  "typings/main",
  "typings/main.d.ts"
  ]
}

接下来,创建(如果不存在)项目本地的global.d.ts文件:

global.d.ts(项目的本地,而不是同名的主TS文件)

export {}

   declare global {
     interface String {
       calcWidth(): number;
     }
   }

extensions.ts(整个文件)

export {}

//don't redefine if it's already there
if (!String.prototype.hasOwnProperty('calcWidth')) {
    String.prototype.calcWidth = function (): number {
      //width calculations go here, but for brevity just return length
      return this.length;
    }
}

然后在你的第一个System.import(文件名)是什么(我的是main.ts)。只需使用一次:

import './extensions'  //or whatever path is appropriate
... 
...

现在,您可以在整个应用中使用界面:

var testString = 'fun test';
console.log(testString.calcWidth());

生成控制台输出:

8

希望这有用。

答案 1 :(得分:1)

不是在html中导入代码,而是将其放在代码的顶部:

import './utils/extensions';

只需将其替换为您的文件路径。

以下是有关模块和导入的更多资源:

TypeScript docs

MDN docs