Learn to implement TypeScript's built-in Pick utility type from scratch. Master type manipulation and generic constraints with this easy-level TypeScript challenge on TypeScriptPro.
Learn how to build one of TypeScript's most fundamental utility types: Pick! 🎯
In this easy-level challenge, you'll implement the built-in Pick<T, K> generic without using the actual Pick utility. This type allows you to create a new type by selecting specific properties from an existing type. It's a cornerstone of TypeScript's type manipulation capabilities and understanding how it works will deepen your knowledge of mapped types and generic constraints.
You'll be constructing a type that picks a set of properties K from type T, creating a new type with only those selected properties. This is incredibly useful for creating partial interfaces or extracting specific fields from larger types.
Implement the built-in Pick<T, K> generic without using it.
Constructs a type by picking the set of properties K from T
For example:
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = MyPick<Todo, 'title' | 'completed'>
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
}Change the following code to make the test cases pass (no type check errors).
To implement the Pick utility type, you need to understand mapped types and the keyof operator.
The solution uses TypeScript's mapped types to iterate over the keys specified in K and extract their corresponding types from T:
type MyPick<T, K extends keyof T> = {
[Key in K]: T[Key]
}Let's break this down:
K extends keyof T ensures that K can only contain keys that actually exist in T[Key in K] iterates over each key in KT[Key] gets the type of property Key from the original type TThis challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount