Skip to content

Distribute 'keyof' union types (take 2) #23645

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
merged 4 commits into from
Apr 24, 2018
Merged

Conversation

ahejlsberg
Copy link
Member

This PR replaces #23626 which I'm abandoning due to a bad merge,

With this PR we transform keyof applied to a union type to an intersection of keyof applied to each union constituent. In other words, we rewrite types of the form keyof (A | B) to `keyof A & keyof

Some examples:

type A = { a: string, c: string };
type B = { b: string, c: string };

type T1 = keyof (A | B);  // "c"
type T2<T> = keyof (T | B);  // (keyof T & "b") | (keyof T & "c")
type T3<U> = keyof (A | U);  // ("a" | keyof U) | ("c" & keyof U)
type T4<T, U> = keyof (T | U);  // keyof T & keyof U
type T5 = T2<A>;  // "c"
type T6 = T3<B>;  // "c"
type T7 = T4<A, B>;  // "c"

This PR is the mirror image of #22300 and finally brings symmetry to the type eqivalences:

keyof (A & B) <==> keyof A | keyof B
keyof (A | B) <==> keyof A & keyof B

Why it took so long to figure out I don't know!

Fixes #23618.

@MartinJohns
Copy link
Contributor

Hey @ahejlsberg, could you update the spec according to the new changes?

@ahejlsberg ahejlsberg merged commit 5d67f8e into master Apr 24, 2018
@ahejlsberg ahejlsberg deleted the distributeKeyofUnion2 branch April 24, 2018 17:09
@zpdDG4gta8XKpMCd
Copy link

out of curiosity what does keyof A & keyof B mean? is a cross product of all prop-names from A and B? if so what is the application?

interface A  { a: number, x: string; }
interface B { b: string; y: number; }
type C = keyof A & keyof B; // <- 'a' & 'b' | 'a' & 'y' | 'x' & 'b' | 'x' & 'y'   ?

@zpdDG4gta8XKpMCd
Copy link

ah, nevermind, missed it in your example

@zpdDG4gta8XKpMCd
Copy link

ah, which is indeed a cross product with all cases being never except the matching ones, duh!

@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants