Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Last active February 12, 2022 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ourmaninamsterdam/a9f7785cb2e9697304c052870faf3bbf to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/a9f7785cb2e9697304c052870faf3bbf to your computer and use it in GitHub Desktop.
Method overloading in TypeScript
// Adapted from https://howtodoinjava.com/typescript/function-overloading
class MiddleEarthResident {
name: string;
constructor(name: string) {
this.name = name;
}
}
class ShireResident extends MiddleEarthResident {
age: number;
constructor(name: string, age: number) {
super(name);
this.age = age;
}
}
class BagginsHouseResident extends ShireResident {
location: string;
constructor(name: string, age: number, location: string) {
super(name, age);
this.location = location;
}
}
function findMiddleEarthResident(name: string): MiddleEarthResident; // Overload Signature 1
function findMiddleEarthResident(name: string, age: number): ShireResident; // Overload Signature 2
function findMiddleEarthResident(name: string, age: number, location: string): BagginsHouseResident; // Overload Signature 3
function findMiddleEarthResident(name: string, age?: number, location?: string): ShireResident | MiddleEarthResident | BagginsHouseResident{ // Implementation Signature
if(name != undefined && age === undefined && location === undefined) {
return new MiddleEarthResident(name);
}
else if(name != undefined && age != undefined && location == undefined) {
return new ShireResident(name, age);
}
else if(name != undefined && age != undefined && location != undefined) {
return new BagginsHouseResident(name, age, location);
}
throw new Error('Nobody found');
}
// By name only
const bilboName = findMiddleEarthResident("Bilbo Baggins");
// bilboName.name
// By name and age
const bilboNameAndAge = findMiddleEarthResident("Bilbo Baggins", 72);
// bilboNameAndAge.name === "Bilbo Baggins"
// bilboNameAndAge.age === 72
// By name, age and location
const bilboNameAgeAndLocation = findMiddleEarthResident("Bilbo Baggins", 72, "The Shire");
// bilboNameAndAge.name === "Bilbo Baggins"
// bilboNameAndAge.age === 72
// bilboNameAndAge.location === "The Shire"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment