Created
August 12, 2024 07:50
-
-
Save narwanimonish/d7bc7683a52a53880a4d24b679973a46 to your computer and use it in GitHub Desktop.
Typescript constructor overload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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