mastrolindus
mastrolindus

Reputation: 673

In Typescript how do you get an element type from an array type, when the array contains different element types?

Let's assume I have an array of data that is of different types:

const input = ["random", 2, {a: "foo", b: "baz"}];

Typescript can automatically infer and extract the types, so for example:

type InputTypeArray = typeof input;

Here typescript knows that InputTypeArray is (string | number | {a: string, b: string})[];

Let's call InputType the type of the elements of the array, that is:

typeof InputType = string | number | {a: string, b: string};

Can I derive InputType from InputTypeArray? In other words, how I would write a function that accept one of the elements of the input as parameter?

const input = ["random", 2, {a: "foo", b: "baz"}];

const myFunction = (element: InputType) => element;

input.map(myFunction);

How do I write "InputType" here ? is there a way to extract it from input?

I know I could workaround by inlining myFunction inside the map call, as typescript will again infer the correct types inside the function. But is there a way to get the type neverthless?

Upvotes: 43

Views: 38007

Answers (2)

Jamon Holmgren
Jamon Holmgren

Reputation: 24392

You can use this format to get the member type:

type InputType = typeof input[number];

You can read more about it (and some other cool tips) here in Steve Holgado's blog article.

Upvotes: 55

Fenton
Fenton

Reputation: 250972

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:

type A = typeof input;

You can use this to get the type of a single item:

type B = typeof input[0];

Upvotes: 25

Related Questions