【问题标题】:Typescript remap deep object keys to function chainTypescript 将深层对​​象键重新映射到函数链
【发布时间】:2020-06-11 17:14:56
【问题描述】:

这适用于映射对象的深层键:

type Car = {
  color: string;
  model: {
     name: string;
  }
}

export type DeepKey<T> = {
   [P in keyof T]: DeepKey<T[P]>;
}

const car: DeepKey<Car> = {};
car.model.name // is ok

但是如何使它成为这样的函数链:

car("model")("name")

类似:

export type DeepFunc<T> = (k: [P in keyof T]) => DeepFunc<T[P]>;

另一种解决方案可能是这样的键数组。 (不过函数方式也很有趣)

["model", "name"] or ["color"]

【问题讨论】:

  • DeepKey&lt;Car&gt; 与仅使用 Car 相比有何意义?在后一个示例中,它是如何在 runtime 实际实现的,更不用说在键入时,它如何知道您何时需要实际值而不是下一层的包装函数?
  • 重点是让typesafe工具获取Car对象的key path。像这里:reddit.com/r/typescript/comments/dt0wzx/… 问题是,这在 IE 上不起作用,因为它基于具有“all catch getter”的代理。所以我想把它改写成可以工作的函数形式。
  • 我不想要这个值,但最后提取整个路径以用于像“model.name”这样的点表示法。这就是上面 reddit 链接上的深度键的工作原理。但我需要它作为函数
  • @luky 是你的目标是能够在 ramda 中拥有类似于path 的功能吗?
  • 是的,这是一种可能的解决方案

标签: typescript typescript-typings


【解决方案1】:

您可以键入一个执行此操作的函数,您的解决方案非常接近,但函数泛型是通用的:

export type DeepFunc<T> = <K extends keyof T>(k: K) => DeepFunc<T[K]>;
type Car = {
  color: string;
  model: {
     name: string;
  }
}
declare var car: DeepFunc<Car>
car("model")("name")
car("model")("name2") // err

Playground Link

请记住,自从?. 运算符出现以来,对安全访问功能的需求已经减少(至少在保护nullundefined 方面)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多