Home > Software engineering >  filter properties based on property type
filter properties based on property type

Time:06-29

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.

CodePudding user response:

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;
}
*/
  • Related