From `T`, pick a set of properties whose type are assignable to `U`. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll build a PickByType utility that selects only the properties from an object type T whose values are assignable to a given type U.
From T, pick a set of properties whose type are assignable to U.
For Example
type OnlyBoolean = PickByType<{
name: string
count: number
isReadonly: boolean
isEnable: boolean
}, boolean> // { isReadonly: boolean; isEnable: boolean; }Change the following code to make the test cases pass (no type check errors).
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
type cases = [
Expect<
Equal<
PickByType<Model, boolean>,
{ isReadonly: boolean; isEnable: boolean }
>
>,
Expect<Equal<PickByType<Model, string>, { name: string }>>,
Expect<Equal<PickByType<Model, number>, { count: number }>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K]
}How it works:
K in T.as clause performs key remapping: for each key, we check whether T[K] extends U (whether the property's value type is assignable to U).K in the output type. If false, we remap it to never, which removes it entirely.T[K] is preserved as-is for all keys that survive the filter.This is the inverse of OmitByType, which removes properties matching the given type. Together, these two utilities demonstrate how key remapping with as enables powerful property filtering patterns.
This challenge helps you understand key remapping in mapped types and how to apply conditional property selection based on value types in real-world scenarios.
This challenge is originally from here.