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?
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 .
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.
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!
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> .
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With