[Typescript] 101. Hard - Typed Get

The get function in lodash is a quite convenient helper for accessing nested values in JavaScript. However, when we come to TypeScript, using functions like this will make you lose the type information. With TS 4.1's upcoming Template Literal Types feature, properly typing get becomes possible. Can you implement it?

For example,

type Data = {
  foo: {
    bar: {
      value: 'foobar',
      count: 6,
    },
    included: true,
  },
  hello: 'world'
}
  
type A = Get<Data, 'hello'> // 'world'
type B = Get<Data, 'foo.bar.count'> // 6
type C = Get<Data, 'foo.bar'> // { value: 'foobar', count: 6 }
 

Accessing arrays is not required in this challenge.

 

/* _____________ Your Code Here _____________ */

type Get<T extends Record<PropertyKey, any>, K extends string> = K extends keyof T
  ? T[K]
  : K extends `${infer P}.${infer U}`
    ? Get<T[P], U>
    : never;

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Get<Data, 'hello'>, 'world'>>,
  Expect<Equal<Get<Data, 'foo.bar.count'>, 6>>,
  Expect<Equal<Get<Data, 'foo.bar'>, { value: 'foobar'; count: 6 }>>,
  Expect<Equal<Get<Data, 'foo.baz'>, false>>,

  Expect<Equal<Get<Data, 'no.existed'>, never>>,
]

type Data = {
  foo: {
    bar: {
      value: 'foobar'
      count: 6
    }
    included: true
  }
  'foo.baz': false
  hello: 'world'
}

 

posted @   Zhentiw  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-15 [Typescript Unit testing] Error Handling with Unknown
2020-11-15 [Typescript v3.9] ts-expect-error
2020-11-15 [Typescript v4.1] Template type literals
2020-11-15 [Typescript v4] Tuple Types && Recursive types
2016-11-15 [Docker] Build a Simple Node.js Web Server with Docker
2016-11-15 [AngularJS NG-redux] Integrate Redux Devtools
2015-11-15 [MongoDB] Introduce to MongoDB
点击右上角即可分享
微信分享提示