Refer to child type in parent when child property is an array

It’s hard to explain, so I made a playground.

type A = {
    a: number,
    complex: {
        b:string,
    },
}

// ok: can refer to the type of complex from A
function withComplexA(prop: A['complex']) {
    // prop. // <-- autocomplete for 'b' works here
}

type B = {
    a: number,
    complex: {
        b: string,
    }[],
}

// not ok: how to refer to the type of complex from B (ignoring the array)?
function withComplexB(prop: B['complex']) {
    // prop. // <-- autocompletes array functions, I want 'b' to be autocompleted here
}

Edit: I accepted an answer below. For completeness, here is another solution I found. (playground)

type C = {
    a: number,
    complex: {
        b: string,
    }[],
}

// solution
type SupaExtract<T> = T extends Array<infer U> ? U : never;

// ok: can refer to the type of complex from C
function withComplexC(prop: SupaExtract<C['complex']>) {
    // prop. // <-- autocomplete for 'b' works here
}

>Solution :

Index into the array with a number:

function withComplexB(prop: B['complex'][number]) {
    prop.b // ok
}

B['complex'][0] and even B['complex'][48179809412] would also work but I like to use number for clarity/explicitness.

Playground

Leave a Reply