简体   繁体   English

如何从接口调用函数?

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

I have a Angular 5 app, and I want to have an interface that defines a function such as this: 我有一个Angular 5应用,我想有一个定义如下功能的接口:

interface PersonInfo {
    getName(): string;
}

And I want another interface that will have a function that has one of its functions return a type of the above: 我希望另一个接口具有一个函数,该函数的其中一个函数返回上述类型:

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

I want to then SOMEHOW use it in my main component, such as the below. 然后,我想在我的主要组件中使用它,如下所示。

@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;
    }
}

The problem is that in console.log(ci.getName()); 问题是在console.log(ci.getName()); , my site gives me an error of TypeError: ci.getName is not a function . ,我的网站给我一个TypeError: ci.getName is not a function错误TypeError: ci.getName is not a function

I'm not sure how to get the getPersonInfo to set the name... and then the getName() to return that name ... and then in the constructor (or in some other function) to call these functions and GET the name. 我不确定如何获取getPersonInfo设置名称...然后getName()返回该名称...然后在构造函数(或其他函数)中调用这些函数并获取名称。 Any help? 有什么帮助吗?

The first issue I see is that you are asserting to TSC that the created "pi" object conforms to the "PersonInfo", but it's missing the "getName()" property. 我看到的第一个问题是,您向TSC断言所创建的“ pi”对象符合“ PersonInfo”,但是缺少“ getName()”属性。

Try this: 尝试这个:

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

    return pi;
}

When possible, avoid using the "foo as Bar" syntax, it seems to be an override to let developers cast a value to a type that the compiler can't guarantee is valid. 尽可能避免使用“ foo as Bar”语法,这似乎是一种替代方法,它使开发人员可以将值强制转换为编译器无法保证有效的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM