我在我的Angular应用程序中扩展typescript字符串接口。我已经添加了一个可以在我的应用程序中访问的方法translate()。 我没有收到任何编译错误。Typescript扩展字符串接口运行时错误
不过,我得到一个运行时错误:
"TypeError: "Translate this string".translate is not a function"
任何想法我可能是做错了?
这里是我执行的截图:
声明:
实施
呼叫:
我在我的Angular应用程序中扩展typescript字符串接口。我已经添加了一个可以在我的应用程序中访问的方法translate()。 我没有收到任何编译错误。Typescript扩展字符串接口运行时错误
不过,我得到一个运行时错误:
"TypeError: "Translate this string".translate is not a function"
任何想法我可能是做错了?
这里是我执行的截图:
声明:
实施
呼叫:
我能解决这个问题。下面是关于如何解决此问题的更新:
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 theglobal.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
这个工作对我来说:
声明接口
interface String {
translate():string
}
使用
String.prototype.translate = function(){
return "boink"
}
let str : string = "test";
let a : string = str.translate();
console.log(a); // logs "boink"
我没有看到任何[延伸](https://www.typescriptlang.org/docs/handbook/classes.html)在这里,所谓的只是一个接口'String'。 – crashmstr
@crashmstr我不需要这里的扩展,因为我在现有的typescript字符串接口中实现了一个新的方法,并将在全局范围内使用它。 – Faisal