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.
For this challenge, you will need to change the following code to make the tests pass (no type check errors).
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,
}
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 K
T[Key]
gets the type of property Key from the original type T
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
This challenge is originally from here.