Create nested mapped type

Viewed 63

I have two types like this:

type ContactPerson = {
  firstName: string
  lastName: string
}
type Customer = {
  companyName: string
  contactPerson: ContactPerson
}

I need to map this type in a generic way to

type Result = {
  companyName: boolean[]
  contactPerson: {
    firstName: boolean[]
    lastName: boolean[]
  }
}

I can map the root level, but how do I handle the nested properties?

type BooleanResult<T> = {
  [Prop in keyof T]: boolean[]
}
1 Answers

I solved it this way:

type BooleanResult<T> = {
  [K in keyof T]: T[K] extends object ? BooleanResult<T[K]> : boolean[]
}

It works as expected but the type info shows this:

type Result = {
    companyName: boolean[];
    contactPerson: BooleanResult<{
        firstName: string;
        lastName: string;
        email: string;
    }>;
}
Related