Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading