Typescript / TSLint:如何在函数返回值上调用typeof?

时间:2018-06-30 16:44:38

标签: typescript tslint

这很好:

const f = () => ({
  a: 5,
  b: "hi",
  c: true
});

const a = f();

type t = typeof a;  // t is {a: number, b: string, c: boolean}

但这不起作用:

const f = () => ({
  a: 5,
  b: "hi",
  c: true
});

type t = typeof (f());  // TSLint error: "Identifier expected"

为什么这行不通?知道如何在不创建a的情况下定义t吗?

1 个答案:

答案 0 :(得分:2)

您可以使用ReturnType条件类型来获取函数的返回类型

const f = () => ({
  a: 5,
  b: "hi",
  c: true
});

type t = ReturnType<typeof f>;  // t is {a: number, b: string, c: boolean }
相关问题