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?
Using type dogList = Array<"dog" | 3 | true>;
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.