Extract scalar fields only from an interface in typescript

Viewed 128

I have the following interface available.

interface User {
  id: string
  name: string
  age: number
  gender: Gender
  hobbies: Hobby[]
  addresses: Address[]
}

Now I want a new type with all the scalar fields as:

interface UserScalars {
  id: string
  name: string
  age: number
  gender: Gender
}

I know that I can use Omit/Exclude here but there are a lot of scalar as well as no-scalars in my case so Omit/Exclude will only make my code uglier.

is this possible in typescript?

1 Answers

Yep. It is possible:

interface User {
  id: string
  name: string
  age: number
  gender: Gender
  hobbies: Hobby[]
  addresses: Address[]
}

type PickByValueType<T, U> = {
  [K in keyof T as T[K] extends U ? K : never]: T[K]
}

type UserScalars = PickByValueType<User, string | number>;

TS Playground

Related