我想根据参数的类型推断返回类型。
这是我的尝试
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()
有一个错误
Type '() => string' is not assignable to type 'string'
其中此行位于if语句中。