How to implement an override method in a TypeScript interface?

I am new to typescript, here is an interface that I would like to implement;

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

sayHello has two signatures that indicate the overload version. I just don’t know how to implement this in the classroom, any help? thanks.

+7
implementation typescript
source share
1 answer

To implement an overloaded function, write all the overload call signatures that you want to see first, and then the implementation signature, which is a superset of all 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 
+8
source share

All Articles