ts中如何获取函数返回值的类型

// ts中可以使用 typeof 获取 变量的类型
const str:string = "foo"
function echo(arg:typeof str):string {
  return arg
}

// 如何获取echo函数的返回值类型?
const bar :typeof echo = '1' // ERROR
// 不能将类型“"1"”分配给类型“(arg: string) => string”。
阅读 17.2k
2 个回答

翻下文档就能解决的事情

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

type ValueType = ReturnType<() => 123> // 123
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题