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

如何定义TypeScript中类型的泛型逆变父类型Contra<T>?

需求与实现目标

原始类型与核心需求

现有TypeScript类型Foo定义如下:

type Foo = {
  name: string,
  bar: {
    buzz: string,
    buzzy: number,
    buzzAldrin: boolean
  },
  active: boolean,
}

我们需要定义一个泛型类型Contra<T>,当传入Foo时,它能生成Foo的逆变父类型(即Foo的部分类型,比如{name: string}、{bar: { buzz: string } }等)。该类型需满足逆变参数的核心条件:

((arg: Contra<Foo>) => any) extends ((arg: Foo) => any)

已实现的双参数校验方案

目前已通过双参数泛型Contra<T,G>实现了该逆变关系的校验:

type Contra<T, G> = ((a: G) => void) extends ((a: T) => void) ? G : never;

type Foo = {
    shape: string,
    name: 'circle',
    b: {
        d: string
    }
}

function test<T, G>(a: T, b: G extends Contra<T, G> ? G : never) {};

let a = {} as Foo;

test(a, {b: {d: 'asd'}}); // 无错误
test(a, {shape: 'test'}) // 无错误
test(a, {shape: 123}) // 类型报错

目标:单参数泛型类型

现在需要将上述逻辑封装为**仅接收单个参数T**的泛型类型Contra<T>,从而简化test函数的定义,实现如下效果:

type Contra<T> = // 待实现的类型定义
function test<T>(a: T, b: Contra<T>) {} // 需达到与双参数版本一致的参数校验效果

内容的提问来源于stack exchange,提问作者Khaled

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:30:53