【问题标题】:How to call a function from an interface?如何从接口调用函数?
【发布时间】:2018-08-18 08:09:05
【问题描述】:

我有一个 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

我不知道如何让getPersonInfo 设置名称...然后getName() 返回该名称...然后在构造函数(或其他一些函数)中调用这些函数并获取名称。有什么帮助吗?

【问题讨论】:

标签: angular typescript interface


【解决方案1】:

我看到的第一个问题是您向 TSC 断言创建的“pi”对象符合“PersonInfo”,但它缺少“getName()”属性。

试试这个:

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

    return pi;
}

如果可能,请避免使用“foo as Bar”语法,这似乎是一种让开发人员将值强制转换为编译器无法保证有效的类型的覆盖。

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多