Skip to content

Instantly share code, notes, and snippets.

@narwanimonish
Created August 12, 2024 07:50
Show Gist options
  • Save narwanimonish/d7bc7683a52a53880a4d24b679973a46 to your computer and use it in GitHub Desktop.
Save narwanimonish/d7bc7683a52a53880a4d24b679973a46 to your computer and use it in GitHub Desktop.
Typescript constructor overload
class Item {
a: string;
b: string;
constructor(a: string, b: string);
constructor(item: {a: string, b: string});
constructor(...args: any[]) {
if (args.length === 2) {
this.a = args[0]
this.b = args[1]
} else if (args.length === 1) {
this.a = args[0].a
this.b = args[0].b
}
console.log(this.a, this.b)
}
}
new Item('a1', 'b1')
new Item({a: 'a2', b: 'b2'})
/*
** OUTPUT **
[LOG]: "a1", "b1"
[LOG]: "a2", "b2"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment