如何为TypeScript中依输入参数返回不同类型的异步函数正确类型标注?
为动态返回类型的异步函数标注TypeScript类型
针对你遇到的场景,有两种简洁且符合严格模式要求的解决方案,分别是函数重载和泛型结合映射类型,以下是具体实现:
方案一:函数重载(直观易懂,适合类型较少的场景)
首先定义User接口:
interface User { id: number; name: string; email: string; }
通过函数重载定义不同参数对应的返回类型:
// 定义函数重载签名,明确每个type对应的返回Promise类型 async function getData(type: "user"): Promise<User>; async function getData(type: "settings"): Promise<string>; async function getData(type: "none"): Promise<null>; // 函数实现,参数类型为所有可能的type字面量联合类型 async function getData(type: "user" | "settings" | "none") { // 模拟实际数据获取逻辑 switch (type) { case "user": return { id: 1, name: "John", email: "john@example.com" }; case "settings": return "dark_mode: enabled"; case "none": return null; default: throw new Error(`不支持的类型:${type}`); } }
使用时,TypeScript会根据传入的type参数自动推断返回类型:
// 返回类型为Promise<User> const user = await getData("user"); // 返回类型为Promise<string> const settings = await getData("settings"); // 返回类型为Promise<null> const empty = await getData("none");
方案二:泛型+映射类型(易于维护,适合类型较多的场景)
先定义一个映射类型,集中管理type与返回类型的对应关系:
interface User { id: number; name: string; email: string; } type DataMap = { user: User; settings: string; none: null; };
然后通过泛型约束和索引类型实现动态返回类型:
async function getData<T extends keyof DataMap>(type: T): Promise<DataMap[T]> { switch (type) { case "user": return { id: 1, name: "John", email: "john@example.com" } as DataMap[T]; case "settings": return "dark_mode: enabled" as DataMap[T]; case "none": return null as DataMap[T]; default: throw new Error(`不支持的类型:${type}`); } }
这种方案的优势在于,当需要新增type和对应的返回类型时,只需要修改DataMap即可,无需额外添加函数签名,扩展性更强。
内容的提问来源于stack exchange,提问作者sMiLeZ
相关产品推荐
相关产品推荐

