Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 656
paul cheung Avatar asked Jul 31 '13 02:07

paul cheung


People also ask

Can you overload methods in TypeScript?

TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.

Can I overload method in interface?

Overloading methods of an interfaceYes, you can have overloaded methods (methods with the same name different parameters) in an interface. You can implement this interface and achieve method overloading through its methods.

What is function overloading TypeScript?

Function overloading in TypeScript lets you define functions that can be called in multiple ways. Using function overloading requires defining the overload signatures: a set of functions with parameter and return types, but without a body. These signatures indicate how the function should be invoked.

How do you do an overloaded method?

Method overloading can be achieved by the following: By changing the number of parameters in a method. By changing the order of parameters in a method. By using different data types for parameters.


1 Answers

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
like image 56
Ryan Cavanaugh Avatar answered Sep 20 '22 09:09

Ryan Cavanaugh