InterviewSolution
| 1. |
Provide the TypeScript syntax to create function overloads. |
|
Answer» Function overloading allows us to define MULTIPLE functions with the same name, as long as their number of parameters or the types of parameters are different. The following example defines TWO OVERLOADS for the function buildDate. The first overload takes a number as a parameter, whereas the SECOND takes three numbers as parameters. These are called overload signatures. The body of the function also called an implementation signature, follows the overload signatures. You can’t call this signature directly, as it’s not visible from the outside. It should be compatible with the overload signatures. function buildDate(timestamp: number): Date;function buildDate(m: number, d: number, y: number): Date;function buildDate(mOrTimestamp: number, d?: number, y?: number): Date {if (d !== undefined && y !== undefined) { return new Date(y, mOrTimestamp, d);} else { return new Date(mOrTimestamp);}}const d1 = buildDate(87654321);const d2 = buildDate(2, 2, 2); |
|