How to extract a type from an array in typescript?

Is there a way to declare a type in typescript that "retrieves" the internal type of the array?

Example:

Let's say I already have something like this in my code base:

export interface Cache { events: Event[], users: User[] } type CacheType = Event[] | User[]; //or maybe: // type TypeOfProperty = T[keyof T]; // type CacheType = TypeOfProperty<Cache>; 

I want this to be equivalent to this:

 type InnerCacheType = Event | User; 

But without manually renaming it every time I add something to Cache or CacheType

Is this possible in Typescript?

+5
source share
1 answer

Suppose you can use TypeScript 2.1 or more, otherwise you cannot achieve what you are looking for.

Also, keep in mind that you take for granted that all properties of the Cache interface will be arrays. If this is not the case, your question becomes meaningless, so I will also make this assumption.

Generally speaking, CacheType can be written as

 type CacheType = Cache[typeof Cache]; 

including any inherited properties. The resulting type is equivalent to Event[] | User[] Event[] | User[] , however, it is not possible to extract the components of an array from this type of union.

The solution uses display types. InnerCacheType you are looking for can be written as

 type InnerCacheType = MappedCacheType[typeof MappedCacheType]; 

Where

 type MappedCacheType = { [P in keyof Cache]: Cache[P][0]; }; 

In fact, the latter type is equivalent

 { events: Event; users: User; } 

Note that TypeScript preserves names in the same way as original ones.

To summarize, without considering your use case, the way to express the type of a component of an array type T is T[0] .

+2
source

Source: https://habr.com/ru/post/1267006/


All Articles