Home > Mobile >  Recursively substitude all properties of the type to a predefined value in Typescript
Recursively substitude all properties of the type to a predefined value in Typescript

Time:02-15

Given the type below:

type Person = {
  name: string
  age: number
  experiece: {
    length: number
    title: string
  }
}

Is it possible to construct the type below:

type FieldsOfPerson = {
  name: true
  age: true
  experience: {
    length: true
    title: true
  }
}

Update:

I came up with a solution below:

type TrueForKeys<T> = {
  [P in keyof T]?: T[P] extends string
    ? true
    : T[P] extends number
    ? true
    : T[P] extends boolean
    ? true
    : TrueForKeys<T[P]>
}

Is there a better way?

The rules for the substitution - everything not an object should be changed to true, recursively

CodePudding user response:

You can use a mapped type with T[key] extends object to differentiate whether to recurse or use true:

type AllTrue<T> = {
    [key in keyof T]: T[key] extends object ? AllTrue<T[key]> : true;
};

Then it's:

type FieldsOfPerson = AllTrue<Person>;

Playground link

  • Related