Access type of the element of an array

I would like to access the type of the element of an array instead of rewriting the type

For example

interface Person{
firstname: string,
lastname: string
phonenumbers: Array<{prefix:number, phonenumber: number}>
}

I would like to access the type of phonenumbers element without redefining it and with a generic way. It could be like this

type PhoneNumber = ArrayElementType<Person["phonenumbers"]>

I tried the solution here, but it does not work for me.


Solution 1:

You can do this directly:

interface PhoneNumber {
    prefix:number; 
    phonenumber: number;
}

interface Person{
    firstname: string,
    lastname: string
    phonenumbers: PhoneNumber[]
}

type ShouldBeNumber = Person['phonenumbers'][number]['phonenumber']

or you can do it generically although it's more complicated:

type ExtractMember<T extends {}, K extends keyof T> = T[K]
type ExtractObjectArrayMember<T, K> = T extends (infer R)[]
  ? K extends keyof R 
    ? ExtractMember<R, K>
    : never
  : never;

type AlsoNumber = ExtractObjectArrayMember<Person['phonenumbers'], 'phonenumber'>

Playground