#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.

In this medium-level challenge, you'll implement a Chainable type that allows you to chain options together.

Warning: This challenge is incredibly hard for being labelled medium. Do not despair if you get stuck.

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.

Change the following code to make the test cases pass (no type check errors).

Loading...

Video Walkthrough

Detailed Explanation

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

type Chainable<R = {}> = {
  option<K extends string, V>(
    key: Exclude<K, keyof R>,
    value: V,
  ): Chainable<Omit<R, K> & Record<K, V>>
  get(): R
}

How it works:

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

This challenge is originally from here.

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