parent
dcf0f94af9
commit
5c1d803892
1 changed files with 9 additions and 19 deletions
@ -1,30 +1,20 @@ |
|||||||
# Constructor Overloading |
# Constructor Overloading |
||||||
|
|
||||||
In TypeScript, you can achieve constructor overloading by using multiple constructors with different parameter lists in a single class. When you create an instance of the class, the constructor with the matching parameter list is called. Here's an example: |
In TypeScript, you can achieve constructor overloading by using multiple constructor definitions with different parameter lists in a single class. Given below is the example where we have multiple definitions for the constructor: |
||||||
|
|
||||||
```typescript |
```typescript |
||||||
class MyClass { |
class Point { |
||||||
property1: number; |
// Overloads |
||||||
property2: string; |
constructor(x: number, y: string); |
||||||
|
constructor(s: string); |
||||||
constructor(property1: number) { |
constructor(xs: any, y?: any) { |
||||||
this.property1 = property1; |
// TBD |
||||||
} |
|
||||||
|
|
||||||
constructor(property1: number, property2: string) { |
|
||||||
this.property1 = property1; |
|
||||||
this.property2 = property2; |
|
||||||
} |
} |
||||||
} |
} |
||||||
``` |
``` |
||||||
|
|
||||||
In this example, we have two constructors with different parameter lists: constructor(property1: number) and constructor(property1: number, property2: string). When you create an instance of the class, the constructor with the matching parameter list is called: |
Note that, similar to function overloading, we only have one implementation of the consructor and it's the only the signature that is overloaded. |
||||||
|
|
||||||
```typescript |
|
||||||
let myInstance1 = new MyClass(10); |
|
||||||
let myInstance2 = new MyClass(10, "Hello"); |
|
||||||
``` |
|
||||||
|
|
||||||
Learn more from the following resources: |
Learn more from the following resources: |
||||||
|
|
||||||
- [Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors) |
- [Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors) |
||||||
|
Loading…
Reference in new issue