[TypeScript] Function Overloads in Typescript
typescript in Function
2023-09-14 09:00:53 时间
It's common in Javascript for functions to accept different argument types and to also return different types. In this lesson we learn how to 'teach' Typescript about these dynamic functions so that we can still benefit from the powerful static type analysis.
const getTasks = (taskname: string, x: any) : any => { if(typeof x === '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 task1 task2.deps; // Runtime Error, deps not exists on task2
In the code above, the IDE cannot help much during the compile time.
But if we use Function overloads, then IDE can help to check error:
interface GroupTask { taskname:string deps:string[] } interface Task { taskname:string fn:Function } function getTasks(taskname:string, x:string[]):GroupTask function getTasks(taskname:string, x:Function):Task function getTasks(taskname:string, x:any):any { if (typeof x === '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 not exist on type 'GrouptTask' task2.deps // Property 'deps' doesn't not exist on type 'Task'
相关文章
- typescript web_typescript在线运行
- Typescript教程_安装typescript
- TypeScript基础常用知识点总结
- TypeScript 贪吃蛇游戏详细教程
- TypeScript学习笔记(一)—— TypeScript入门
- typescript error TS2322: Type ‘Timeout‘ is not assignable to type ‘number‘.
- TypeScript笔记
- TypeScript 中 as const 是什么
- 让你更好使用 Typescript 的11个技巧
- 掌握 TypeScript:20 个提高代码质量的最佳实践
- 【TypeScript】条件语句
- 开心档之TypeScript 联合类型
- 查询优化Oracle中IN查询的技巧(oracle优化in)
- MySQL中的IN函数详解(mysql中的in)
- MySQL的IN操作符对于查询中给定的值列表长度是有限制的(mysql中in长度限制)
- MySQL中使用IN关键字时,字符串的长度有限制吗(mysql中in长度)
- MySQL使用IN查询时数量超限问题的解决方法(mysql中in超过数量)
- MySQL中IN操作存在漏洞(mysql中in有漏)
- MYSQL中IN关键字如何高效处理大量数据(mysql中in关键字)
- MySQL查询语句中的不存在关键字NOT IN(mysql 不存在 in)
- Oracle如何优化IN查询以提高效率(oracle优化in查询)
- 的区别Oracle中IN与的异同探究(oracle中in和=)
- 提升Oracle IN操作中的性能改进(oracle in的性能)
- Oracle 中的 IN 子句使用技巧(oracle in 子句)