-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
SuggestionAn idea for TypeScriptAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds
Description
TypeScript Version: 2.8-rc
Search Terms:
typescript Conditional Types narrow type primitive union
Code
type SwapType<T extends number | string> = T extends number ? string : number;
function swapper<T extends number | string>(id: T): SwapType<T>{
switch (typeof id) {
case "number":
return id.toString();
case "string":
return Number(id);
default:
throw new TypeError("Not supported");
}
}
const idNumber = swapper("123");
const idString = swapper(123);
console.log(`Number ${typeof idNumber} and string ${typeof idString}`);
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
Griffork
Metadata
Metadata
Assignees
Labels
SuggestionAn idea for TypeScriptAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds