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

如何从Migration的up方法返回值推断down方法参数类型

实现Migration类型的自动类型推断

我正在编写一个基础迁移工具——核心是一个包含up()和down()方法的对象。执行迁移时,会保存up()函数的返回数据,随后将其作为参数传入down()方法,示例代码如下:

const myMigration: Migration<number[]> = {
  async up() {
    return [1, 2, 3];
  },
  async down(data) {
    data.forEach(number => console.log(number)); // 1, 2, 3
  },
};

目前我定义的Migration类型如下:

type Migration<T = void> = {
  up(): Promise<T>
  down(data: T): Promise<void>
}

当前的问题是必须显式指定泛型类型,我希望down()方法的data参数类型能自动从up()方法的await返回值中推断出来。以下是我几次失败的尝试:

尝试1:给down方法添加泛型

// 无效
type Migration<T = void> = {
  up(): Promise<T>
  down<U extends T = T>(data: U): Promise<void>
}

尝试2:通过ReturnType推断类型

// 无法从同一实例推断类型
type Migration<T = void> = {
  up(): Promise<T>
  down(data: Awaited<ReturnType<Migration["up"]>>): Promise<void>
}

期望实现的效果

希望能无需显式指定泛型,让down()的data参数类型自动推断:

const myMigration: Migration = {
  async up() {
    return [1, 2, 3];
  },
  async down(data) {
    // data的类型被自动推断为number[]
    data.forEach(number => console.log(number)); // 1, 2, 3
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:12