Reputation: 2638
I want to infer a return type based on the parameter's type.
Here is my try
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"
Unfortunately I have no idea why typescript fails on line return () => arg()
with an error Type '() => string' is not assignable to type 'string'
where this line is in a if statement.
Upvotes: 2
Views: 1043
Reputation: 7080
Use 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");
Upvotes: 2