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

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

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:

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

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

>Solution :

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

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