在我的 angular2 项目中,我尝试使用 typescript 扩展 string 类的原型(prototype)。 这是我的代码:
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>
最佳答案
我能够在没有 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(filename) 中(我的是 main.ts)。只需使用一次:
import './extensions' //or whatever path is appropriate
...
...
现在,您可以在整个应用程序中使用您的界面:
var testString = 'fun test';
console.log(testString.calcWidth());
产生控制台输出:
8
希望对您有所帮助。
关于typescript - typescript 中的扩展方法(系统),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36432983/