Suhail Ibn Nisar
Suhail Ibn Nisar

Reputation: 57

Extract scalar fields only from an interface in typescript

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?

Upvotes: 3

Views: 448

Answers (1)

Alexander Alexandrov
Alexander Alexandrov

Reputation: 1372

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

Upvotes: 3

Related Questions