打字稿中的扩展方法(系统) [英] Extension methods in typescript (system)
问题描述
在我的angular2项目中,我试图使用Typescript扩展 string 类的原型. 这是我的代码:
In my angular2 project I'm trying to extend the prototype of the string class using typescript. This is my code:
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的内容帮助也可以帮助我),但是在运行时,我会得到未定义包含".
With this code the project compiles (also the content assist of Visual Studio Code assists me) but at run-time I get a 'contains is not defined'.
我做错了什么?
非常感谢
PS:这是我的tsconfig:
PS: this is my 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"
]
}
编辑
我注意到将 js 文件导入 index.html 是可行的,但是我不喜欢这种方法.
I noticed that importing the js file in index.html it works, but I don't like this approach.
<script src="app/source/utils/extensions.js"></script>
推荐答案
我能够在没有TS错误(1.8.9),Angular2(2.0.0-beta.12)错误和工作函数调用的情况下正常运行使用以下模板:
I was able to get it working with no TS errors (1.8.9), Angular2 (2.0.0-beta.12) errors, and working function call using the following template:
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文件:
Next, create (if one doesn't exist) a global.d.ts file local to your project:
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( filename )是(我的是main.ts)中.只需使用一次:
Then in your whatever your first System.import(filename) is (mine is main.ts). Just use once:
import './extensions' //or whatever path is appropriate
...
...
现在,在整个应用中,您可以使用界面:
Now, throughout your app you can use your interface:
var testString = 'fun test';
console.log(testString.calcWidth());
产生控制台输出:
8
希望这会有所帮助.
这篇关于打字稿中的扩展方法(系统)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!