Hivaga
Hivaga

Reputation: 4506

Typescript conditional typings strange error case

Conditional typing in Typescript is not very intuitive. The code bellow returns an error in the Typescript playground. Can someone explain why since this seems like a perfect easy example for the conditional typings.

function process<T extends string | null>(text: T): T extends string ? string : null {
  return text;
}

//Type 'T' is not assignable to type 'T extends string ? string : null'.
//Type 'string | null' is not assignable to type 'T extends string ? string : null'.
//Type 'null' is not assignable to type 'T extends string ? string : null'.(2322)

Upvotes: 2

Views: 68

Answers (1)

Federkun
Federkun

Reputation: 36924

Typescript is not able to narrow the return type of a function with conditional types, which has parameters defined as a union.

function process<T extends string | null>(text: T): T extends string ? string : null {
  // the problem here is that type guard can't narrow over the type parameter
  if (typeof text === 'string') {
      return text; // error
  }

  return null; // error
}

The best you can do is to return text as any; and go on with your life. The alternative here is to use overloads to accomplish what you want.

Upvotes: 1

Related Questions