Update: based on @jerico's answer below

The following type alias will return the type of the elements in an array or tuple:

type ArrayElement<ArrayType extends readonly unknown[]> = 
  ArrayType extends readonly (infer ElementType)[] ? ElementType : never;

So these examples would work:

type A = ArrayElement<string[]>; // string
type B = ArrayElement<readonly string[]>; // string
type C = ArrayElement<[string, number]>; // string | number
type D = ArrayElement<["foo", "bar"]>; // "foo" | "bar"
type E = ArrayElement<(P | (Q | R))[]>; // P | Q | R

type Error1 = ArrayElement<{ name: string }>; 
//                         ^^^^^^^^^^^^^^^^
// Error: Type '{ name: string; }' does not satisfy the constraint 'readonly unknown[]'.

Explanation

The type guard (the bit in the angle brackets) ArrayType extends readonly unknown[] says that we expect the type parameter ArrayType to be at least a readonly array (it also accepts a mutable array) so that we can look at its element type.

This prevents passing in a non-array value, as in the final example, which prevents ArrayElement ever returning never.

Note that readonly unknown[] is syntax added in TypeScript 3.4; for earlier versions use ReadonlyArray<unknown>.

On the right-hand side, the conditional expression asks the compiler to fill in the value of ElementType in the pattern readonly ElementType[] and return ElementType if it can, or never if it can't.

Since the type guard at the beginning means we will only ever be passed a value which matches this pattern, it's guaranteed always to match and never to return never.

Previous answer

type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType[number];
Answer from Will Madden on Stack Overflow
Top answer
1 of 9
215

Update: based on @jerico's answer below

The following type alias will return the type of the elements in an array or tuple:

type ArrayElement<ArrayType extends readonly unknown[]> = 
  ArrayType extends readonly (infer ElementType)[] ? ElementType : never;

So these examples would work:

type A = ArrayElement<string[]>; // string
type B = ArrayElement<readonly string[]>; // string
type C = ArrayElement<[string, number]>; // string | number
type D = ArrayElement<["foo", "bar"]>; // "foo" | "bar"
type E = ArrayElement<(P | (Q | R))[]>; // P | Q | R

type Error1 = ArrayElement<{ name: string }>; 
//                         ^^^^^^^^^^^^^^^^
// Error: Type '{ name: string; }' does not satisfy the constraint 'readonly unknown[]'.

Explanation

The type guard (the bit in the angle brackets) ArrayType extends readonly unknown[] says that we expect the type parameter ArrayType to be at least a readonly array (it also accepts a mutable array) so that we can look at its element type.

This prevents passing in a non-array value, as in the final example, which prevents ArrayElement ever returning never.

Note that readonly unknown[] is syntax added in TypeScript 3.4; for earlier versions use ReadonlyArray<unknown>.

On the right-hand side, the conditional expression asks the compiler to fill in the value of ElementType in the pattern readonly ElementType[] and return ElementType if it can, or never if it can't.

Since the type guard at the beginning means we will only ever be passed a value which matches this pattern, it's guaranteed always to match and never to return never.

Previous answer

type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType[number];
2 of 9
142

Since 2.1, typescript supports [ ] operator for types. The official name is indexed access types, also called lookup types, and it works like this:

type A = {a: string, b: number} [];

type AElement = A[0];

let e: AElement = {x: 0}; //error TS2322: Type '{ x: number; }' is not 
                       //assignable to type '{ a: string; b: number; }'
🌐
Total TypeScript
totaltypescript.com › get-the-type-of-an-array-element
This Crazy Syntax Lets You Get An Array Element's Type | Total TypeScript
September 2, 2024 - Learn how to extract the type of an array element in TypeScript using the powerful `Array[number]` trick.
Discussions

Get array element as type?
You can abuse some quirks of generics to do this: https://github.com/microsoft/TypeScript/issues/30680 type Narrowable = string | number | boolean | symbol | undefined | void | null declare function func(arr: T): T[number] const val = func([1, 2]) // ^? const val: 1 | 2 More on reddit.com
🌐 r/typescript
13
9
October 28, 2022
typescript - How to get type of array items? - Stack Overflow
I think you're confused between the run-time typeof result, and the TypeScript type of an array element. More on stackoverflow.com
🌐 stackoverflow.com
In Typescript how do you get an element type from an array type, when the array contains different element types? - Stack Overflow
You can extract it by pointing at an array member, so while you are using the below code to get the type of the array: ... It was very trivial in the end :) I was expecting for some reasons that typeof input[0] would return string, as that is the type of the first element, but obviously it ... More on stackoverflow.com
🌐 stackoverflow.com
typescript - How can I get the type of array items? - Stack Overflow
I think you're confused between the run-time typeof result, and the TypeScript type of an array element. More on stackoverflow.com
🌐 stackoverflow.com
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › indexed-access-types.html
TypeScript: Documentation - Indexed Access Types
We can combine this with typeof to conveniently capture the element type of an array literal: ... key];Type 'key' cannot be used as an index type.'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?2538 2749Type 'key' cannot be used as an index type.'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?Try · However, you can use a type alias for a similar style of refactor:
🌐
Reddit
reddit.com › r/typescript › get array element as type?
r/typescript on Reddit: Get array element as type?
October 28, 2022 -

Is it possible to have a function that takes a parameter of type T[] and has a return type of "element of the parameter" (not the general type T)?

In other words, if I write "const x = myFunc([1, 2])", can I type myFunc in a way that the compiler knows x can only be 1 or 2 at compile time?

I tried for a while but could not figure it out. The only thing that worked was declaring the array "as const" before passing it in, but I would like to solve this through typing the function instead, if possible.

🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-get-types-from-arrays-in-typescript
How To Get Types From Arrays in TypeScript? - GeeksforGeeks
September 26, 2024 - We will explore different methods ... types, and tuple inference. ... The typeof operator allows us to know the type of an array's elements by referencing the array variable directly....
🌐
DEV Community
dev.to › diballesteros › quick-ts-tips-how-to-extract-a-type-from-an-array-5afk
Quick TS Tips: How to extract a type from an array - DEV Community
November 21, 2021 - Here the infer keyword from typescript (which must be used with extends) to declaratively introduce a new generic type U based on the given array. Now let’s assume that the TStuff type is an array and we want to extract a singular TStuff. We could then supply the type of TStuff[] to ArrayElement
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-array-element-type
Get the Element type from an Array type in TypeScript | bobbyhadz
To get the element type from an array type, use a condition type with an `infer` declaration to infer the type of an element in the array.
Find elsewhere
🌐
TypeScript Tutorial
typescripttutorial.net › home › typescript tutorial › typescript array type
TypeScript Array Type
August 24, 2024 - Since an element in a string array is a string, TypeScript infers the type of the skill variable to string as shown in the output. TypeScript arrays have the same properties and methods as JavaScript arrays. For example, the following uses the length property to get the number of elements in ...
🌐
YouTube
youtube.com › watch
Typescript: Get Element Type for Array #typescript #typescriptdevelopment #reactjs #reactdeveloper - YouTube
How to get the type of a single element in an array in TypeScript.⭐ Get my full-stack Next.js with Express & TypeScript course: https://codinginflow.com/next...
Published   December 24, 2023
🌐
Tutorial Teacher
tutorialsteacher.com › typescript › typescript-array
TypeScript Arrays
2. Using a generic array type, Array<elementType>. let fruits: Array<string> = ['Apple', 'Orange', 'Banana']; Both methods produce the same output. Of course, you can always initialize an array like shown below, but you will not get the advantage ...
🌐
Melvin George
melvingeorge.me › blog › get-object-type-from-array-of-objects-typescript
How to get the object type from an array of objects in TypeScript? | MELVIN GEORGE
January 24, 2022 - To get the object type from an array of objects first, we can use the typeof type operator followed by the array variable name or array literal followed by writing a square brackets symbol ([]) and inside the square brackets, we can write the ...
🌐
xjavascript
xjavascript.com › blog › typescript-get-array-element-type
TypeScript: Getting the Array Element Type — xjavascript.com
To get the element type of an array, TypeScript provides a built-in utility type called ArrayElementType (not a real built-in name, but we can create a type helper).
🌐
Fjolt
fjolt.com › article › typescript-array-type
TypeScript Array Type
July 9, 2022 - If we have an array, we can define its type in TypeScript by using the notation type[]. For example, the below variable arrayType is expected to be an array of strings.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 28046
Creating types from values in array · Issue #28046 · microsoft/TypeScript
October 22, 2018 - const values = ['A', 'B'] type Foo = OneOf<values> // Is there a way of doing this? const v1: Foo = 'A' // This should work const v2: Foo = 'D' // This should give me an error since 'D' doesn't exist in values ... const values = { A: 'A', B: 'B' } type Foo = keyof typeof values const v1: Foo = 'A' const v2: Foo = 'D' // Type '"D"' is not assignable to type '"A" | "B"' ... Link to playground http://www.typescriptlang.org/play/#src=let vals1 = ['A', 'B'] type Foo1 = OneOf<vals1> // Is there a way of doing this?
Author   G2Jose
🌐
TkDodo
tkdodo.eu › blog › array-types-in-type-script
Array Types in TypeScript
August 19, 2023 - Let’s help out by actually implementing that function and look at the error we’re getting: ... This doesn’t mean anything to me, at all. To solve the puzzle: it’s about operator precedence. The [] binds stronger than the | operator, so now we’ve made items to be of type string OR number[]. What we want is: (string | number)[], with parentheses, to make our code work. The generic version doesn’t have this problem because it separates Array from its content with the angle brackets anyway.
🌐
Miyauchi
miyauchi.dev › en › posts › typesafe-array-element
Getting array elements type-safely with TypeScript | miyauci.me
July 2, 2021 - In this article, I will introduce such type-safe retrieval of array and string elements. To conclude first, I have published a function project of fonction, which is a functional utility package, so please use it. It is TypeScript-first, and supports multiple runtimes such as Deno, Node.js, and browsers, so it can be used in basically any environment.