[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'
}
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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