在打字稿中:如何为功能提取单独的输入和输出类型



对于此功能:

function first(x: number, y: string) {
return {
    a: x,
    b: y
  };
}
function second(z: typeof first()) {
  return {
    c: 6,
    ...z
  }
}

typeof first()当然是无效的,

我想在second的签名中使用first的推断输出类型。是否有可能(我假设没有,但希望感到惊讶(

谢谢!

否,目前无法提取函数的返回类型。

github上有一个线程,不过在其中讨论了这一点。您可以在这里看到它。

您现在可以做的是定义要在第一个函数的返回类型和第一个函数接收到的参数的类型。它也更加明确,更容易理解。

interface ReturnType {
    a: number,
    b: string
}
function first(x: number, y: string): ReturnType {
    return {
        a: x,
        b: y
    };
}
function second(z: ReturnType) {
    return {
        c: 6,
        ...z
    }
}

最新更新