I have a String Union that looks like:
type AlphabetLike = 'a' | 'b' | 'c' | 'zeta' | 'beta' | 'gamma' | 'mu';
I want to be able to construct the type
type Alphabet = 'a' | 'b' | 'c'. I could do this by using Exclude and removing zeta, beta, gamma, and mu but that's a lot of things to remove and if more values are added to AlphabetLike, it changes Alphabet. I want to know if my value from "AlphabetLike" is ever removed from that type.
Is there a way to do an Include instead of an Exclude?
There is an Extract<T, U> utility type which acts like the opposite of the Exclude<T, U> utility type:
type AlphabetLike = 'a' | 'b' | 'c' | 'zeta' | 'beta' | 'gamma' | 'mu';
type Alphabet = Extract<AlphabetLike, 'a' | 'b' | 'c' | 'zzz'>;
// type Alphabet = "a" | "b" | "c"
Note that nothing forces the second argument (called U here) to either Extract<T, U> or Exclude<T, U> to contain only elements from the first argument (called T here). Hence that 'zzz' above doesn't have an effect on anything.
Playground link to code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With