If we consider the given type structure:
type Person = {
name: string
age: number
experience: {
length: number
title: string
}
}
Can we create a type like this:
type FieldsOfPerson = {
name: true
age: true
experience: {
length: true
title: true
}
}
Here is my proposed solution:
type TrueForKeys<span class="highlight"><</span>T<span class="highlight">></span> = {
[P in keyof T]?: T[P] extends string
? true
: T[P] extends number
? true
: T[P] extends boolean
? true
: TrueForKeys<span class="highlight"><</span>T[P]<span class="highlight">></span>;
}
Do you think there's a better approach to accomplish this?
The guidelines for substitution are clear - any non-object should be converted to true
, with recursion in mind.