TypeScript Version: 2.8-rc
Search Terms:
typescript Conditional Types narrow type primitive union
Code
typeSwapType<Textendsnumber|string>=Textendsnumber ? string : number;functionswapper<Textendsnumber|string>(id: T): SwapType<T>{switch(typeofid){case"number": returnid.toString();case"string": returnNumber(id);default:
thrownewTypeError("Not supported");}}constidNumber=swapper("123");constidString=swapper(123);console.log(`Number ${typeofidNumber} and string ${typeofidString}`);Expected behavior:
To be able to return the narrowed type from the union and have the compiler not mentioning that the returned type is not assignable the type that has conditional type.
Actual behavior:
The compiler produce this error:
src/conditionalType.ts(6,4): error TS2322: Type 'string' is not assignable to type 'SwapType<T>'.
src/conditionalType.ts(8,4): error TS2322: Type 'number' is not assignable to type 'SwapType<T>'.
The generated JavaScript is good.
Playground Link:
Link
TypeScript Version: 2.8-rc
Search Terms:
typescript Conditional Types narrow type primitive union
Code
Expected behavior:
To be able to return the narrowed type from the union and have the compiler not mentioning that the returned type is not assignable the type that has conditional type.
Actual behavior:
The compiler produce this error:
The generated JavaScript is good.
Playground Link:
Link