簡體   English   中英

打字稿擴展字符串接口運行時錯誤

[英]Typescript Extend String interface Runtime Error

我在Angular應用程序中擴展了Typescript String接口。 我添加了一個方法translate(),該方法可在我的整個應用程序中訪問。 我沒有任何編譯錯誤。

但是,出現運行時錯誤:

“ TypeError:“翻譯此字符串”。翻譯不是函數”

有什么想法我可能做錯了嗎?


這是我的實現的屏幕截圖:

宣言:

在此處輸入圖片說明

履行

在此處輸入圖片說明

呼叫:

在此處輸入圖片說明

我能夠解決此問題。 這是有關如何解決此問題的更新:


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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM