#12Medium

Chainable Options

Chainable options are commonly used in Javascript. But when we switch to TypeScript, can you properly type it? Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

Chainable options are commonly used in Javascript. But when we switch to TypeScript, can you properly type it? 🎯

In this medium-level challenge, you'll chainable options are commonly used in javascript. but when we switch to typescript, can you properly type it?. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

This challenge will teach you essential skills for advanced TypeScript development and type-level programming.

For this challenge, you will need to change the following code to make the tests pass (no type check errors).

Challenge Instructions: Chainable Options

Medium

Chainable options are commonly used in Javascript. But when we switch to TypeScript, can you properly type it?

In this challenge, you need to type an object or a class - whatever you like - to provide two function option(key, value) and get(). In option, you can extend the current config type by the given key and value. We should about to access the final result via get.

For example

declare const config: Chainable
 
const result = config
.option('foo', 123)
.option('name', 'type-challenges')
.option('bar', { value: 'Hello World' })
.get()
 
// expect the type of result to be:
interface Result {
foo: number
name: string
bar: {
value: string
}
}

You don't need to write any js/ts logic to handle the problem - just in type level.

You can assume that key only accepts string and the value can be anything - just leave it as-is. Same key won't be passed twice.

Loading...

Video Walkthrough

Detailed Explanation

To create a chainable interface, we track the accumulated type:

type Chainable<T = {}> = {
  option<K extends string, V>(key: K, value: V): Chainable<T & { [P in K]: V }>
  get(): T
}

How it works:

This challenge helps you understand TypeScript's advanced type system and how to apply this concept in real-world scenarios.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount

This challenge is originally from here.