这很好:
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吗?
答案 0 :(得分:2)
您可以使用ReturnType
条件类型来获取函数的返回类型
const f = () => ({
a: 5,
b: "hi",
c: true
});
type t = ReturnType<typeof f>; // t is {a: number, b: string, c: boolean }