You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:17:31