Find Item of Specific Type in Array

How to get type of array items?

If you're looking to how to extract { name: string; test: number; } type, you can simply create alias to "item at index":

type Foo = Array<{ name: string; test: number; }>;
type FooItem = Foo[0];

or

type FooItem = Foo[number];

Typescript: Retrieve element type information from array type

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

Finding a value in an array by type in TypeScript

You can use the generic in both the type of the class argument and the return value as follows:

function find<A extends Animal>(animals: Animal[], cls: new() => A): A | undefined {
return animals.find((value): value is A => value instanceof cls);
}

Note that, by using a type predicate as the return value from the find callback, we don't need a type assertion any more. This is much safer - you might not find a cls instance in animals, you're potentially returning undefined as A in your current implementation.

The generic can be inferred from the second argument when you call this:

find(animals, Dog);

Playground

How can I find an item of a specific type in an array

In Swift it's really easy, use first(where method of the array. Like so:

let cat = pets.first { $0 is Cat }

Or, extended version:

let cat = pets.first { (animal) -> Bool in
return animal is Cat
}

The first and second piece of the code does the same thing.

Find a value in an array of objects in Javascript

You can loop over the array and test for that property:

function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

How to get the Type of an Array item

As you discovered, both work well enough. I would use CustomArray[number] since that basically says 'Give me the type if I index with any number' while CustomArray[0] says 'Give me the type if I index with 0'. The two seem similar, but if CustomArray is a tuple type, results may actually be different:

export type CustomArray = [string, ...number[]];

type I0 = CustomArray[0] // string
type I1 = CustomArray[1] // number
type INumber = CustomArray[number] // string | number

Playground Link

GetType() on Array item?

Well, you can get the element type of the array:

Type type = array.GetType().GetElementType();

(That's not quite the same as getting the types of the items in the array - an object[] may be entirely populated with strings, for example.)

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

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


Related Topics



Leave a reply



Submit