Reputation: 57
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
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>;
Upvotes: 3