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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With