Typescript函数返回类型怎样根据传入参数值的不同而改变? - 知乎

文章分享到的地方: Typescript函数返回类型怎样根据传入参数值的不同而改变? - 崮生的回答 - 知乎
我这里有两种方案,一种是重载一种是类型推断
我更喜欢第二种,但存在一些问题,希望知道的朋友指点一下
在线尝试_www.typescriptlang.org/zh/play
ts
type p = 't' | 'h' function test(p: 't'): number function test(p: 'h'): string function test(p: 't' | 'h'): number | string { if (p == "t") { return 3 } else { return "" } } // 这个函数的类型是符合题目要求的但内部实现会报错,我不知道该怎么在不使用 any 和 @ts-ignore 的情况下实现 function test2(p:T): T extends 't' ? number : string { if (p == "t") { return 3 // Type 'number' is not assignable to type 'T extends "t" ? number : string'. } else { //@ts-ignore return "" } }
宁逍遥 给出的方案要优雅的多
在官网查看并理解narrowing和mapping type这两个知识点 ts/paly
typescript
interface Values { a: string b: number [key: string]: unknown } type P = keyof Values type T = Values['a'] type S = Values['b'] function isKeys(key: unknown): key is P { return key === 'a' || key === 'b' } function getValue(key: Key): Values[Key] function getValue(key: string): unknown { const store: Values = { a: "Hello", b: 123, } if (isKeys(key)) { return store[key] } return store[key] } // c is string const c = getValue('a') // d is number const d = getValue('b') // others is unknown const e = getValue("fuck the world")