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.
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).
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:
get() returns the final accumulated typeoption calls return a new Chainable with the added property, but calls do not repeat keys (due toExclude<K, keyof R>)option remove old key K from R when passing to self, essentially overwriting with new key&)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.
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