Custom TypeScript PropertiesOfType Function
Learn to create a custom TypeScript type called PropertiesOfType that improves the sort function.
We'll cover the following
We’ve built a powerful generic search function, capable of sorting in both ascending and descending fashion, but there is still an improvement that can be made. A problem arises from the fact that we use both the greater than (>
) and less than (<
) symbols in our genericSort
function. These operators don’t make much sense when comparing JavaScript primitive types like Symbol
, boolean
, null
, and so on. In fact, the list of types that should be allowed as property
to genericSort
is much smaller than those that shouldn’t.
Custom PropertiesOfType
type
One way to restrict the type of property without having to write more code in genericSort
is to create a custom type that only allows the types that make sense when compared with >
and <
operators. In this case, those are string
, Date
, and number types.
We’ll call this type PropertiesOfType
. The PropertiesOfType
will accept two generic types—Type
, the type of which properties we’ll want to allow and the ValueTypes
, all the types of the values allowed in Type
.
Then, using the keyof
operator, we can check the type of each value of Type. If the value of the property at that key extends our ValueTypes
, we return the key type K
. Otherwise, we return never
, which removes that key from our list of allowed keys. The PropertiesOfType
type looks like this:
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy