Home > Blockchain >  Transform class or interface properties types recursively
Transform class or interface properties types recursively

Time:09-08

Is possible to transform Class/Interface properties into certain types? My goal is to transform all primitive properties into boolean and array-like properties into element-like types where also properties are transformed like in the parent object.

Example:

interface Skill {
  name: string;
  level: 'beginner' | 'intermediate' | 'advanced';
}

interface User {
  id: number;
  email: string;
  skills: Skill[];
}

/**
 * TO
 */

interface QueriedSkill {
  name: boolean;
  level: boolean;
}

interface QueriedUser {
  id: boolean;
  email: boolean;
  skills: QueriedSkill;
}

The goal is to create such an interface dynamically:

type QueriedUser = TransformToQueried<User>

Want to use this for my graphql server for optimized data resolution

CodePudding user response:

That's gonna look something like this:

type Queried<T> = T extends object ? {
    [K in keyof T]: T[K] extends ReadonlyArray<unknown> ? Queried<T[K][number]> : T[K] extends object ? Queried<T> : boolean;
} : boolean;

It's a recursive type that turns all non-objects into type boolean. In the case of arrays, it unwraps it into its elements and operates on that instead.

I don't think it needs to work with tuples but if it does, you can comment on here for an edit.

Playground

  • Related