Typescript 类型体操 —— 实现 Chainable Option

681 阅读1分钟

要求

某些场景下,我们经常会写出一些链式调用的代码,本题用一个简单的递归介绍链式调用下的类型关系,要求每次多次链式调用后,得到的类型是可定义的。

// your code 
// type YourTypeFunc...

declare const a: YourTypeFunc
const result = a
  .option('foo', 123)
  .option('bar', { value: 'Hello World' })
  .option('name', 'type-challenges')
  .get()

// result 
type res = typeof result 
// 期望res的类型和Expected相似
type Expected = {
  foo: number
  bar: {
    value: string
  }
  name: string
}

你只需要在类型层面实现这个功能 - 不需要实现任何 TS/JS 的实际逻辑。你可以假设 key只接受字符串而 value 接受任何类型,你只需要暴露它传递的类型而不需要进行任何处理。同样的 key 只会被使用一次。

知识点

  1. In TypeScript 4.1, conditional types can now immediately reference themselves within their branches, making it easier to write recursive type aliases.

知识链接

  1. 知识点: 递归类型
  2. 知识点: 范型与函数

问题 & 解答

  1. Chainanle Options
  2. 解答