Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in TypeScript to say "Include" (opposite of Exclude)?

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?

like image 403
William Neely Avatar asked Feb 04 '26 13:02

William Neely


1 Answers

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

like image 131
jcalz Avatar answered Feb 06 '26 05:02

jcalz