简体   繁体   中英

how to implement overload method in TypeScript Interface?

i am new to typescript, here is a interface which i'd like to implement;

interface IThing{
    name:string;
    age:number;
    sayHello:{
        (name:string):string;
        (age:number):number;
    }
}

sayHello has two signatures which indicates overload version. i just don't know how to implement that in a class, any help? thanks.

To implement an overloaded function, write all the overload call signatures you want to be visible first, followed by an implementation signature that is a superset of all the overload signatures. Example:

class Thing implements IThing {
    // Implement the name and age fields
    name: string;
    age: number;

    // Overload signature #1
    sayHello(name: string): string;
    // Overload signature #2
    sayHello(age: number): number;
    // Implementation signature, not visible to external callers
    sayHello(arg: any): any {
        if(typeof arg === 'string') {
            return this.name;
        } else if(typeof arg === 'number') {
            return this.age;
        } else {
            throw new Error('sayHello can only take string or a number');
        }
    }
}

var x = new Thing();
var n = x.sayHello('world'); // n: string
var a = x.sayHello(42); // a: number
var e = x.sayHello(false); // error: false is not string or number

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