Typescript conditional typings strange error case

63 Views Asked by At

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)
1

There are 1 best solutions below

1
Federkun On

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.