[英]Typescript Extend String interface Runtime Error
我能夠解決此問題。 這是有關如何解決此問題的更新:
1.創建文件
global.d.ts
並在其中添加接口擴展定義。
export { };
declare global
{
interface String
{
/**
* Translates the given string according to the culture provided.
* @param cultureName The culture name of the translation target.
* @returns The translated string.
*/
translate(cultureName: string): string;
}
}
2.使用接口擴展方法定義創建另一個文件。 就我而言,我將其命名為
string.extensions.ts
/**
* Translates the given string according to the culture provided.
* @param cultureName The culture name of the translation target.
* @returns The translated string.
*/
String.prototype.translate = function(cultureName: string): string
{
const inputValue = this;
// Do the translation here
const translatedValue = 'Willkommen bei meiner App'; // Only for example
return translatedValue ;
};
3.在您的應用程序啟動文件中,以我的情況為
main.ts
,添加對global.d.ts
的引用以及包含擴展方法定義的文件。
/// <reference path="app/core/extensions/global.d.ts" />
//...
import './app/core/extensions/string.extensions';
您只需要在項目( main.ts
)中一次導入此文件,然后就可以在代碼中的任何位置使用它。
4.在我的AppComponent中使用示例
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `
Original Value: <h3>{{ originalValue }}</h3>
Translated Value: <h3>{{ translatedValue }}</h3>
`
})
export class AppComponent {
private originalValue:string;
private translatedValue:string;
constructor() {
this.originalValue = 'Welcome to my App';
this.translatedValue = 'Welcome to my App'.translate('de-DE');
}
}
這是解決此煩人問題所需要做的一切。
以下是工作中的矮人的鏈接: Plunker演示
這對我有用:
聲明一個接口
interface String {
translate():string
}
用法
String.prototype.translate = function(){
return "boink"
}
let str : string = "test";
let a : string = str.translate();
console.log(a); // logs "boink"
我想您的聲明位於單獨的文件中。 它仍然使用基本聲明。 代碼無法訪問。 嘗試使用從文件或此文件直接導入。
///<reference path="test.d.ts"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.