Borislav Hadzhiev
Last updated: Feb 28, 2022
Check out my new book
Use a union type to declare an array that only accepts specific values, e.g.
const arr2: ('a' | 'b' | 'c')[] = []
. A union type is formed from two or more
other types or literals. The array in the example can only contain the strings
a
, b
and c
.
type NumbersLessThan5 = 1 | 2 | 3 | 4; const arr: NumbersLessThan5[] = []; arr.push(1); arr.push(2); arr.push(3); arr.push(4);
We used a union type to create an array that only accepts specific values.
The array in the example can only contain the numbers 1-4
. If we try to add a
number that is not contained in the union type to the array, we'd get an error.
type NumbersLessThan5 = 1 | 2 | 3 | 4; const arr: NumbersLessThan5[] = []; // ⛔️ Error: Argument of type '5' is not // assignable to parameter of type 'NumbersLessThan5'.ts(2345) arr.push(5);
This works in the same way when using string literals.
type FirstThreeLetters = 'a' | 'b' | 'c'; const arr2: FirstThreeLetters[] = []; arr2.push('a'); arr2.push('b'); arr2.push('c'); // ⛔️ Error: Argument of type '"d"' is not // assignable to parameter of type 'FirstThreeLetters'.ts(2345) arr2.push('d');
The values do not have to be of the same type. You can use the same approach in the unlikely scenario that you have mixed arrays.
type Mixed = 'a' | 'b' | 1; const arr2: Mixed[] = []; arr2.push('a'); arr2.push('b'); arr2.push(1);
Union types are quite useful in TypeScript, in fact the boolean
type is just
an alias for the union true | false
.