[英]How to declare return type based on parameter's type in Typescript
我想根据参数的类型推断返回类型。
这是我的尝试
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()
上失败并出现错误Type '() => string' is not assignable to type 'string'
where this line is in a if statement。
使用function 过载:
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.