Peter
Peter

Reputation: 38455

filter properties based on property type

Is there someway to construct a type based on a generic type, where i extract all properties of a specific type?

class Test {
  value1!: Date
  value2!: number
  value3!: Date
  value4!: string
}
type FilterProperties<T, TFieldType> = //some magic here where we only pick fields that have the type TFieldType
const onlyDates = {} as FilterProperties<Test, Date>

FilterProperties<Test, Date> should only have the properties value1 and value3 when this works as expected.

I tried to get this to work with Extract and Pick but they both work on a key basis instead of type.

Upvotes: 1

Views: 408

Answers (1)

nook
nook

Reputation: 1884

You can use this method:

class Test {
  value1!: Date
  value2!: number
  value3!: Date
  value4!: string
}

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

type B = FilterProperties<Test, Date>
/*
type B = {
    value1: Date;
    value3: Date;
}
*/

Upvotes: 3

Related Questions