TypeScript函数如何从输入推断泛型参数关联的键类型
TypeScript泛型函数实现:依赖键的类型推断与返回值捕获
需求:实现一个泛型函数,接收的对象参数中,某一键的类型依赖另一键的类型,且作为类型变量的键需从函数输入中自动推断,同时要捕获完整的推断类型用于处理函数返回值。
原版
interface Input<T extends 'a' | 'b' = 'a' | 'b'> { t: T u: T extends 'a' ? (1|2) : (3|4) } const create = <$Input extends Input>(x: $Input) => x // create({ t: 'a', u: /* 这里应该自动提示为1|2,目前无法实现 */ }) create({t:'a',u:1}) create({t:'a',u:2}) // @ts-expect-error create({t:'a',u:3}) // @ts-expect-error create({t:'a',u:4})
更新版
//declare global { interface Foo { A: { hasThing: true } } //} //declare global { interface Foo { B: { hasThing: false } } //} type Name = keyof Foo interface Input<$Name extends Name = Name> { t: $Name u: Foo[$Name] extends true ? (1|2) : (3|4) } // 构造函数 const create = <$Input extends Input>(x: $Input): $Input['u'] => { return undefined as any } // 测试用例 // ---------------------------------------------- let x = create({t:'A', u:1}) x = 1 // <- 应该通过类型检查 // @ts-expect-error x = 2 // ---------------------------------------------- const y = create({t:'A', u:2}) // @ts-expect-error x = 1 x = 2 // <- 应该通过类型检查 // ---------------------------------------------- // @ts-expect-error create({t:'A', u:3}) // ---------------------------------------------- // @ts-expect-error create({t:'A', u:4})
内容的提问来源于stack exchange,提问作者Jason Kuhrt
相关产品推荐
相关产品推荐

