typescript - fn 重载的空类型保护
问题描述
我可以在 Typescript 中做一个重载,cb
其中说如果Error
为空则Id
必须定义或者如果Error
定义则Id
必须为空?
function passId(cb: (err: Error, id: null) => void): any
function passId(cb: (err: null, id: number) => void): any
function passId(cb: (err: Error | null, id: number | null) => void){
// implementation ...
}
// usage: if error defined and the fn returns
// then it means because of the type definition number must be defined.
const foo = () => {
if(err){
return
}
// id must be defined by here..
let a: number = id
}
解决方案
推荐阅读
- php - 如何在 web.php 中定义路由以在 Laravel 中显示 404 视图?
- c++ - node-gyp build 给出未解决的外部符号错误
- .net - Azure Function V2 - 错误:与服务器的连接异常终止
- php - 基于类别顺序在 laravel eloquent 关系中获得一行的特定类别中有多少张图像?
- asp.net - 如何从 ASP.NET 页面返回 JSON 值
- laravel - 在 Laravel Blade 文件中的多个数组上使用 foreach 循环对齐 UI 元素时出现问题
- spring - 原生查询结果映射到spring jpa中的自定义对象
- c# - 使用 ms 访问从 MemoryStream 读取位图时抛出异常
- javascript - java脚本嵌套过滤函数
- c# - 当我尝试解析无效值时,Enum.ToObject 返回默认值