How to get the value type of an array type?

If I have type type foo = Array<{ name: string; test: number; }> type foo = Array<{ name: string; test: number; }> type foo = Array<{ name: string; test: number; }> , is it possible to get the type of values โ€‹โ€‹in the array, in this case the interface. I know there is keyof to get the keys, is there something similar for the values?

+11
source share
4 answers

If you want to learn how to extract the type { name: string; test: number; } { name: string; test: number; } { name: string; test: number; } , you can simply create an alias for the element by index:

 type Foo = Array<{ name: string; test: number; }>; type FooItem = Foo[0]; 

or

 type FooItem = Foo[number]; 
+11
source

Starting with TypeScript 2.8, you can also do this with the infer :

 type GetElementType<T extends Array<any>> = T extends (infer U)[] ? U : never; 

For instance:

 // ElementType === string type ElementType = GetElementType<string[]>; 

And this also works inside mapped types, where different properties can have different types:

 type MapArraysToValues<T extends { [key: string]: any[] }> = { [key in keyof T]: GetElementType<T[key]>; }; // Output === { x: number, y: string } type Output = MapArraysToValues<{ x: number[], y: string[] }>; 
+10
source

Despite Alexeyโ€™s answer, it would be useful to know that if an instance of this generic type provides at least one member of the type you want to extract, you can use typeof to query the type of this element.

For a general Array type can be requested from any element of the array: enter image description here

Note that line 27 exists only at design time so as not to create any errors, even if arr empty or undefined at run time.

+1
source

We can also use the indexed access operator as follows:

 const someArray = [ { foo: '', bar: '', baz: '' }, { foo: '', bar: '', baz: '' } ]; // indexed access operator type SomeArray = typeof someArray[number]; 

You can find out about them here: https://www.typescriptlang.org/docs/handbook/advanced-types.html.

The second operator is T [K], the indexed access operator .

0
source

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


All Articles