在Typescript

时间:2016-12-20 21:27:55

标签: typescript

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

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

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

type ToastFunctionType = typeof toast

此类型将是

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

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

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

{ a: string; b: string; }

1 个答案:

答案 0 :(得分: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;

2018年2月更新

在即将发布的2.8版本中,有some new language features可以在不涉及虚拟变量和函数的情况下实现。

此示例使用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
相关问题