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

Merged type not inferred as a mapped type argument #18354

Closed
dwickern opened this issue Sep 9, 2017 · 2 comments
Closed

Merged type not inferred as a mapped type argument #18354

dwickern opened this issue Sep 9, 2017 · 2 comments
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@dwickern
Copy link

dwickern commented Sep 9, 2017

TypeScript Version: 2.5.x, 2.6.0-dev.20170908

When passed as an argument, T & U evaluates to T, and the type U is discarded.

declare function f<T, Key extends keyof T>(obj: {[K in keyof T]: T[K]}, key: Key): T[Key];

declare const obj: { a: string } & { b: string };
f(obj, 'a');
f(obj, 'b'); // error

Playground link


Workarounds

Specify the type arguments explicitly:

f<typeof obj, keyof typeof obj>(obj, 'b');

An identity type mapping can be used to create an intermediate type

type Fix<T> = {[P in keyof T]: T[P]}

declare const obj: Fix<{ a: string } & { b: string }>;
f(obj, 'a');
f(obj, 'b');

Related issue typed-ember/ember-typings#32

@ahejlsberg ahejlsberg self-assigned this Sep 9, 2017
@ahejlsberg ahejlsberg added the Bug A bug in TypeScript label Sep 9, 2017
@ahejlsberg ahejlsberg added this to the TypeScript 2.6 milestone Sep 9, 2017
@ahejlsberg
Copy link
Member

ahejlsberg commented Sep 9, 2017

This is an issue with how we break down intersection types in type inference. Here's a simpler repro:

declare function f<T>(x: { prop: T }): T;

declare const a: { prop: string } & { prop: number };
declare const b: { prop: string & number };

f(a);  // string
f(b);  // string & number

We obviously shouldn't deliver different results above. Both should be string & number.

@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Sep 9, 2017
dwickern added a commit to typed-ember/ember-typings that referenced this issue Sep 10, 2017
@dwickern
Copy link
Author

Thanks for the quick fix. I can confirm this is working in [email protected]

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

2 participants