簡體   English   中英

如何從接口調用函數?

[英]How to call a function from an interface?

我有一個Angular 5應用,我想有一個定義如下功能的接口:

interface PersonInfo {
    getName(): string;
}

我希望另一個接口具有一個函數,該函數的其中一個函數返回上述類型:

interface Parser{
    getPersonInfo(document: string): PersonInfo;
}

然后,我想在我的主要組件中使用它,如下所示。

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage implements PersonInfo, Parser {

    constructor() {
        const pi: PersonInfo = this.getPersonInfo('test');
        console.log(pi.getName());
    }
    public getName(): string{
        return 'getname';
    }
    public getPersonInfo(document: string): PersonInfo{
        const pi: PersonInfo  = {
            getName(){
                return 'getPersonInfo - getName()';
            }
        };

        return pi;
    }
}

問題是在console.log(ci.getName()); ,我的網站給我一個TypeError: ci.getName is not a function錯誤TypeError: ci.getName is not a function

我不確定如何獲取getPersonInfo設置名稱...然后getName()返回該名稱...然后在構造函數(或其他函數)中調用這些函數並獲取名稱。 有什么幫助嗎?

我看到的第一個問題是,您向TSC斷言所創建的“ pi”對象符合“ PersonInfo”,但是缺少“ getName()”屬性。

嘗試這個:

public getPersonInfo(document: string): PersonInfo {
    const pi: PersonInfo = {
        getName() {
            return 's';
        }
    };

    return pi;
}

盡可能避免使用“ foo as Bar”語法,這似乎是一種替代方法,它使開發人員可以將值強制轉換為編譯器無法保證有效的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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