Lasharela
Lasharela

Reputation: 1547

Get type from Array<T>

I have an auto generated type,

export type ReferralListByCustomerQuery = { referralListByCustomer?: Array<{ code: string, referredByID: string } |  undefined> |  undefined };

But I need a type of Item of Array:

type WhatINeed = { code: string, referredByID: string } | undefined

So, I know how to extract array type:

type IncludingArray = ReferralListByCustomerQuery[referralListByCustomer]

but question is how to extract Array Item. after google:

type OnlyItem = IncludingArray[number] is not working

Upvotes: 2

Views: 1060

Answers (1)

CollinD
CollinD

Reputation: 7573

This is the same as T[number], but you can extract like this also:

type ElementOf<T> = T extends Array<infer U> ? U : never

You can then use it like this

type SomeArrayType = Array<{foo: string}>;
type TheTypeOfThoseElements = ElementOf<SomeArrayType>;
type SomeOtherType = ElementOf<typeof someVariable>;

You might also need to omit the | undefined from the type, which can be done like this:

type DefinitelyDefined<T> = Exclude<T, undefined>

Upvotes: 5

Related Questions