简体   繁体   English

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

[英]Export return type of function in Typescript

I have a function that builds an object, like this: 我有一个构建对象的函数,如下所示:

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

I can define the type of the function as 我可以将函数的类型定义为

type ToastFunctionType = typeof toast

This type would be 这种类型

() => { a: string; b: string; }

However, I only want the type of the return value. 但是,我只想要返回值的类型。 Is it possible to extract the type of the return value of toast? 是否可以提取吐司返回值的类型? In my use case, the actual values of the objects are using pretty verbose generic type arguments. 在我的用例中,对象的实际值使用了非常详细的泛型类型参数。 Type inference gets them just right and I would like to avoid maintaining a very verbose interface (that I need to export). 类型推断使它们恰到好处,我想避免维护一个非常详细的接口(我需要导出)。

What I want in the case of toast is just 在吐司的情况下我想要的只是

{ a: string; b: string; }

Yes it's possible. 是的,这是可能的。 The trick is to have some value somewhere which is declared with the type you need (return type of toast() ), without actually calling toast() . 诀窍是在某个地方使用你需要的类型声明一些值(返回类型为toast() ),而不实际调用toast() You can do that by introducing another function that returns a value of appropriate type (the actual value is null), then creating a variable and assigning it the value returned by that function, then getting typeof of that. 您可以通过引入适当的返回类型的值(实际值为null)另一种功能,然后创建一个变量,并为其分配由函数返回的值,然后让做typeof这一点。

I could not find a way without adding unused variable, but since the variable is initialized by null that's immediately returned from the function, I suppose that runtime overhead is negligible. 我没有找到一种方法而没有添加未使用的变量,但由于变量是由函数立即返回的null初始化的,我认为运行时开销可以忽略不计。 Here is the code: 这是代码:

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;

UPDATE Feb 2018 更新2018年2月

In the upcoming 2.8 release, there are some new language features that make it possible without involving dummy variables and functions. 在即将发布的2.8版本中,有一些新的语言功能可以在不涉及虚拟变量和函数的情况下实现。

This example compiles with typescript@next: 这个例子用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM