【问题标题】:How to declare return type based on parameter's type in Typescript如何在 Typescript 中根据参数类型声明返回类型
【发布时间】:2021-05-09 17:34:02
【问题描述】:

我想根据参数的类型推断返回类型。

这是我的尝试

type Arg = string | (() => string)

function fn1(arg: Arg): typeof arg extends Function ? () => string : string {
  if (typeof arg === "function") {
    return () => arg();
  }

  return arg;
}

const a = fn1("hello") // a should be "string"
const b = fn1(() => "hello") // b should be () => "string"

Link to demo

不幸的是,我不知道为什么 typescript 在 return () => arg() 行失败,并在 if 语句中出现错误 Type '() => string' is not assignable to type 'string'

【问题讨论】:

  • 为什么不直接返回arg本身呢?
  • 这只是一个例子 :) 在“现实生活”中,arg 函数获取一个参数并进行一些计算。
  • 这能回答你的问题吗? stackoverflow.com/questions/50642020
  • 这个函数的目的是什么?看来是身份危机了。为什么不只创建两个函数:type FxnA = (string) => string;type FxnB = (Function) => Function。然后您的 typeof 检查可以在这些函数被调用之前被拉到它们之外。

标签: javascript typescript


【解决方案1】:

使用function overloads:

function fn1(arg: string): string;
function fn1(arg: () => string): () => string;
function fn1(arg: string | (() => string)){
  if (typeof arg === 'function'){
    return () => arg();
  }
  return arg;
}

const a = fn1("hello");
const b = fn1(() => "hello");

Link to demo.

【讨论】:

  • 示例 2 不起作用。 cd 应该调用 fn2
  • @Nenad 我的错。从答案中删除。
  • 让第二个示例工作会很好,但由于某种原因它不起作用。如果你限制函数的返回类型,那么你会在函数体中得到错误——返回类型不匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2017-06-20
  • 2020-05-28
  • 2021-07-08
  • 2021-04-01
相关资源
最近更新 更多