この問題を修正できました。ここでは、この問題を解決する方法についての更新は、次のとおりです。
1. Create a file global.d.ts
and add the interface extension definitions there.
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. Create another file with the interface extension methods definition. In my case I named it 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. In your app boot file, in my case its main.ts
, add a reference to the global.d.ts
and the file containing your extension methods definitions.
/// <reference path="app/core/extensions/global.d.ts" />
//...
import './app/core/extensions/string.extensions';
あなたは自分のプロジェクトに一度、このファイルをインポートする必要が
(main.ts
)コード内のどこでも使用できます。あなたはこの厄介な問題を解決するために行う必要があるすべてです
4. Example use in my 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へのリンクです:Plunker Demo
私は、ここで[拡張](https://www.typescriptlang.org/docs/handbook/classes.html)と呼ばれるだけのインターフェースをいずれも表示されません'String'。 – crashmstr
@crashmstr既存のtypescript Stringインターフェイスに新しいメソッドを実装していて、それをグローバルに使用しようとしているので、ここで拡張する必要はありません。 – Faisal