【发布时间】: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"
不幸的是,我不知道为什么 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