Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional Types and Narrowing Type Fail to Return #22628

Closed
MrDesjardins opened this issue Mar 16, 2018 · 2 comments
Closed

Conditional Types and Narrowing Type Fail to Return #22628

MrDesjardins opened this issue Mar 16, 2018 · 2 comments
Labels
Suggestion An idea for TypeScript Too Complex An issue which adding support for may be too complex for the value it adds

Comments

@MrDesjardins
Copy link

MrDesjardins commented Mar 16, 2018

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

@jack-williams
Copy link
Collaborator

Related comment: here

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Too Complex An issue which adding support for may be too complex for the value it adds labels Mar 16, 2018
@RyanCavanaugh
Copy link
Member

There's no possible way we could soundly reason about this in anything except the most trivial special cases.

@microsoft microsoft locked and limited conversation to collaborators Jul 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Suggestion An idea for TypeScript Too Complex An issue which adding support for may be too complex for the value it adds
Projects
None yet
Development

No branches or pull requests

3 participants