feerlay
feerlay

Reputation: 2638

How to declare return type based on parameter's type in Typescript

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"

Link to demo

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

Answers (1)

yqlim
yqlim

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");

Link to demo.

Upvotes: 2

Related Questions