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)
Typescript is not able to narrow the return type of a function with conditional types, which has parameters defined as a union.
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.