use*_*528 14 prototype typescript typescript1.8 angular
在我的angular2项目中,我正在尝试使用typescript扩展字符串类的原型.这是我的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
使用此代码编译项目(也是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"
]
}
Run Code Online (Sandbox Code Playgroud)
编辑
我注意到在index.html中导入js文件可行,但我不喜欢这种方法.
<script src="app/source/utils/extensions.js"></script>
Run Code Online (Sandbox Code Playgroud)
Pau*_*l M 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"
]
}
Run Code Online (Sandbox Code Playgroud)
接下来,创建(如果不存在)项目本地的global.d.ts文件:
global.d.ts(项目的本地,不是同名的主TS文件)
export {}
declare global {
interface String {
calcWidth(): number;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的第一个System.import(文件名)是什么(我的是main.ts).只需使用一次:
import './extensions' //or whatever path is appropriate
...
...
Run Code Online (Sandbox Code Playgroud)
现在,在整个应用程序中,您可以使用您的界面:
var testString = 'fun test';
console.log(testString.calcWidth());
Run Code Online (Sandbox Code Playgroud)
生成控制台输出:
8
Run Code Online (Sandbox Code Playgroud)
希望这是有帮助的.
不用导入 html 中的代码,只需将其放在代码的顶部:
import './utils/extensions';
Run Code Online (Sandbox Code Playgroud)
只需将其替换为您的文件路径即可。
以下是有关模块和导入的更多资源:
| 归档时间: |
|
| 查看次数: |
9141 次 |
| 最近记录: |