You might have met the case when an app provided you with a union type, such as:
type UserRoleType = ‘admin’ | ‘user’ | ‘newcomer’;
Then, in another part of the app, we fetch user data and check its role. For this case, we need to create an array:
const ROLES: UserRoleType = [‘admin’, ‘user’, ‘newcomer’];
Looks tiring, doesn’t it? We need to repeat union-type values inside our array. It would be great to have a feature to retrieve a type from an existing array to avoid duplication. Fortunately, indexed types help here as well.
First of all, we need to declare our array using a const assertion to remove the duplication and make a read-only tuple.
const ROLES = [‘admin’, ‘user’, ‘newcomer’] as const;
Then, using the
typeof operator and
number type, we create a union type based on the array value.
type RolesType = typeof ROLES[number]; // ‘admin’ | ‘‘user’ | ‘‘newcomer’;
You may be confused about this solution, but as you may know, arrays are object-based constructions with numeric keys. That’s why, in this example,
number is used as the index access type.