首页 > 解决方案 > 如何正确使用映射类型进行函数签名

问题描述

根据我想输入返回的参数类型。类似于函数重载,但使用映射类型。

const requestX = async(
    id?: string | undefined,
): Promise<(typeof id) extends string ? X: X[]> =>
    fetch(......)

但是,返回总是键入为X[]。正确的方法是什么?

标签: typescripttypescript-typings

解决方案


除非您按照 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>

推荐阅读