TypeScript types to restrict array values

1.1k Views Asked by At

Can I use TypeScript types to restrict array inputs to certain elements?

For example, if I wanted to create a type that is an array that could hold any number of elements, but the elements are restricted to the values: "dog", 3, and true, could I do this without allowing any other string, number, or boolean values?

1

There are 1 best solutions below

0
Matthew Keller On

Using type dogList = Array<"dog" | 3 | true>; to define the type then assigning it to a variable with const list1: dogList = ["dog", 3, true, true]; works properly.