TypeScript如何为函数类型查找表正确声明返回值类型
问题原因
TypeScript 暂时无法自动将泛型参数T对应的查找表函数返回值,和ReturnType<typeof lookupTable[T]>做精准的类型关联,当你调用lookupTable[p]()时,TS会将返回值推导为string | number联合类型,无法匹配泛型约束下的精确返回类型,因此抛出类型不匹配错误。
方案1:添加类型断言(最简单快捷)
逻辑上可以确定返回值和声明的返回类型完全匹配,直接用类型断言跳过TS的自动推导校验即可:
const lookupTable = { A: () => "foo", B: () => 1, }; function findInTable<T extends "A" | "B">( p: T ): ReturnType<typeof lookupTable[T]> { return lookupTable[p]() as ReturnType<typeof lookupTable[T]>; } const isString: string = findInTable("A"); // 类型正常推导为string const isNumber: number = findInTable("B"); // 类型正常推导为number
方案2:使用函数重载(无类型断言,类型更安全)
如果不想使用类型断言,可以通过函数重载提前声明每个入参对应的返回类型,TS会自动匹配重载规则:
const lookupTable = { A: () => "foo", B: () => 1, }; // 重载声明 function findInTable(p: "A"): string; function findInTable(p: "B"): number; function findInTable(p: "A" | "B") { return lookupTable[p](); } const isString: string = findInTable("A"); // 类型正常 const isNumber: number = findInTable("B"); // 类型正常
内容的提问来源于stack exchange,提问作者Quadear
相关产品推荐
相关产品推荐

