45

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?

2 Answers 2

56

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.

Sign up to request clarification or add additional context in comments.

3 Comments

To me, this generic method seems a better solution than explicitly using an index (like input[0] given in another solution), since it won't fail when the array is empty.
Typescript infers a generic number anyway if you use an integer index, since we are talking about build time typings, not run time values. Consequently both syntaxes are logically equal. I agree that this is clearer though.
When I saw how Prettier auto-formats this, I realized it's not exactly what we think it is. We may think it's getting [number] from input, then getting the type of input[number]. But in reality, it's actually getting the type of input then getting the type of [number] from that parent type. Ergo: type InputType = (typeof input)[number];. PS: This should be the accepted solution @mastrolindus
26

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];

2 Comments

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 wouldn't make sense at a type-level. Thanks!
You can also do type B = typeof input[number]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.