Skip to content

Conditional Types and Narrowing Type Fail to Return #22628

Closed
@MrDesjardins

Description

@MrDesjardins

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions