在Typescript中导出函数的返回类型

use*_*864 8 typescript

我有一个构建对象的函数,如下所示:

function toast() {
  return {
    a: "a",
    b: "b"
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以将函数的类型定义为

type ToastFunctionType = typeof toast
Run Code Online (Sandbox Code Playgroud)

这种类型

() => { a: string; b: string; }
Run Code Online (Sandbox Code Playgroud)

但是,我只想要返回值的类型.是否可以提取吐司返回值的类型?在我的用例中,对象的实际值使用了非常详细的泛型类型参数.类型推断使它们恰到好处,我想避免维护一个非常详细的接口(我需要导出).

在吐司的情况下我想要的只是

{ a: string; b: string; }
Run Code Online (Sandbox Code Playgroud)

art*_*tem 12

是的,这是可能的.诀窍是在某个地方使用你需要的类型(返回类型toast())声明一些值,而不实际调用toast().您可以通过引入另一个返回适当类型值的函数(实际值为null),然后创建一个变量并为其赋值该函数返回的值,然后获取该函数typeof来实现.

我没有找到一种方法而没有添加未使用的变量,但由于变量是由null函数立即返回的,所以我认为运行时开销可以忽略不计.这是代码:

function toast() {
  return {
    a: "a",
    b: "b"
  }
}

function getReturnType<R> (f: (...args: any[]) => R): {returnType: R} {
    return null!;
}

// dummy variable, used for retrieving toast return type only
let toastType = getReturnType(toast);

export type ToastReturnType = typeof toastType.returnType;
Run Code Online (Sandbox Code Playgroud)

更新2018年2月

在即将发布的2.8版本中,有一些新的语言功能可以在不涉及虚拟变量和函数的情况下实现.

这个例子用typescript @ next编译:

export function z() {
    return {a: 1, b: '2'}
}

export function v() {
}

type ReturnType<T extends (...args: any[]) => any> = 
    T extends (...args: any[]) => infer R ? R : never;

export type RZ = ReturnType<typeof z>; // { a: number; b: string; }
export type RV = ReturnType<typeof v>; // void
Run Code Online (Sandbox Code Playgroud)

  • @Louis修复了,谢谢.当你必须使用带有"null"的非空断言运算符时,这是极少数情况之一. (3认同)
  • 请当前用户注意,通用的“ReturnType”现已内置到该语言中!很方便。 (3认同)