Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 661
mastrolindus Avatar asked Feb 09 '18 10:02

mastrolindus


People also ask

How do you determine the type of element in an array?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

How can we retrieve an element from an array?

Retrieving the first and last elements in a simple array can most easily be done by using the ARRAY_FIRST and ARRAY_LAST functions. Retrieving the next or previous elements in a simple array can most easily be done by using the ARRAY_PRIOR and ARRAY_NEXT functions.

How would you define type in TypeScript for array of objects?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you give an array a type?

To create an array type you can use Array<Type> type where Type is the type of elements in the array. For example, to create a type for an array of numbers you use Array<number> . You can put any type within Array<Type> .


1 Answers

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]; 
like image 108
Fenton Avatar answered Oct 15 '22 06:10

Fenton