InterviewSolution
| 1. |
Does Typescript Support Function Overloading As Javascript Doesn’t Support Function Overloading? |
|
Answer» Yes, TypeScript does support function OVERLOADING. But the implementation is odd. When you overload in TypeScript, you only have one implementation with multiple signatures. class Customer { The first signature has one parameter of type number whereas the second signature has a parameter of type string. The third function contains the actual implementation and has a parameter of type any. The any data type can take any type of data. The implementation then checks for the type of the supplied parameter and executes a DIFFERENT piece of code BASED on supplier parameter type. OR You can also use union type introduced in TypeScript 1.4. Union types let you represent a value which is one of multiple types. add(a:string|number) { Using union type, you can typically remove the need for an overload. Yes, TypeScript does support function overloading. But the implementation is odd. When you overload in TypeScript, you only have one implementation with multiple signatures. class Customer { The first signature has one parameter of type number whereas the second signature has a parameter of type string. The third function contains the actual implementation and has a parameter of type any. The any data type can take any type of data. The implementation then checks for the type of the supplied parameter and executes a different piece of code based on supplier parameter type. OR You can also use union type introduced in TypeScript 1.4. Union types let you represent a value which is one of multiple types. add(a:string|number) { Using union type, you can typically remove the need for an overload. |
|