It ' s common in Javascript for functions to accept different argument types and to also return different types. In this lesson we learn "teach ' Typescript about these dynamic functions so we can still benefit from the Powe rful static type analysis.
Const GETTASKS = (taskname:string, x:any): any = { if(typeofx = = = ' function '){ return{taskname, fn:x}; } if(Array.isarray (x)) {return{taskname, deps:x}; }};const Task1= Gettasks (' taskname1 ', [' dep1 ', ' DEP2 ']); Const TASK2= Gettasks (' taskname2 ',function() {}); Task1.fn (); //Runtime Error, fn NOT exists on Task1Task2.deps;//Runtime Error, deps not exists on Task2
In the code above, the IDE cannot help much during the compile time.
If we use the Function overloads, then the IDE can help to check the error:
interface grouptask {taskname:string deps:string[]}interface Task {taskname:string fn: Function}function Gettasks (taskname:string, x:string[]): Grouptaskfunction gettasks (taskname:string, x:function): Task functiongettasks (taskname:string, X:any): any {if(typeofx = = = ' function ') { return{taskname, fn:x}; } if(Array.isarray (x)) {return{taskname, deps:x}; }}const Task1= Gettasks (' taskname1 ', [' dep1 ', ' DEP2 ']); Const TASK2= Gettasks (' taskname2 ',function() {}); Task1.fn//Property ' fn ' doesn ' t is exist on type ' Groupttask 'Task2.deps//Property ' deps ' doesn ' t is exist on type ' Task '
[TypeScript] Function Overloads in Typescript