简体   繁体   中英

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:

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()); , my site gives me an error of 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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