typescript - 如何正确使用映射类型进行函数签名
问题描述
根据我想输入返回的参数类型。类似于函数重载,但使用映射类型。
const requestX = async(
id?: string | undefined,
): Promise<(typeof id) extends string ? X: X[]> =>
fetch(......)
但是,返回总是键入为X[]
。正确的方法是什么?
解决方案
除非您按照 Aleksey L. 的建议使用重载,否则您需要一个泛型类型参数,否则typeof id
将静态解析到string | undefined
这对映射没有帮助。
泛型示例:
const requestX = async <ID extends string | undefined = undefined>(id?: ID)
: Promise<ID extends string ? X : X[]> =>
fetch(...);
const x = requestX() // Promise<X[]>
const y = requestX('123'); // Promise<X>
推荐阅读
- php - 如何将索引添加到数组而不是让键从零开始?
- php - php 将文件发布到 ServiceStack API
- vb.net - VB.NET Windows 窗体应用程序中可重用的 UI 代码
- python - 如何将 curl 命令作为 python 请求发布?
- html - 如何通过离线模式打开的网页访问二维码
- sql - 将行分组为新行并在 SQL 中求和
- focus - requestFocusInaWindow() 不工作 - 我做错了什么?
- c++ - 为什么代码片段会引发浮点异常?
- python-3.x - 使用熊猫将字符串转换为浮点数
- haskell - 如何在 GHCi 中配置 Vi 模式?