Back to Type Challenges

README

questions/00012-medium-chainable-options/README.md

latest2.4 KB
Original Source
<!--info-header-start--><h1>Chainable Options </h1><blockquote><p>by Anthony Fu <a href="https://github.com/antfu" target="_blank">@antfu</a></p></blockquote><p><a href="https://tsch.js.org/12/play" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.zh-CN.md" target="_blank"></a> <a href="./README.ja.md" target="_blank"></a> <a href="./README.ko.md" target="_blank"></a> </p><!--info-header-end-->

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

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

<!--info-footer-start-->

<a href="../../README.md" target="_blank"></a> <a href="https://tsch.js.org/12/answer" target="_blank"></a> <a href="https://tsch.js.org/12/solutions" target="_blank"></a> <!--info-footer-end-->