[Typescript] 96. Hard - Optional Keys

Implement the advanced util type OptionalKeys<T>, which picks all the optional keys into a union.

 

/* _____________ Your Code Here _____________ */

type OptionalKeys<T extends Record<PropertyKey, any>> = keyof {
  [Key in keyof T as T[Key] extends Required<T>[Key] ? never: Key]: any
}


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

type cases = [
  Expect<Equal<OptionalKeys<{ a: number; b?: string }>, 'b'>>,
  Expect<Equal<OptionalKeys<{ a: undefined; b?: undefined }>, 'b'>>,
  Expect<Equal<OptionalKeys<{ a: undefined; b?: undefined; c?: string; d?: null }>, 'b' | 'c' | 'd'>>,
  Expect<Equal<OptionalKeys<{}>, never>>,
]

 

posted @   Zhentiw  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-11 [Spring] Factory Pattern
2020-11-11 [Javascript] Broadcaster + Operator + Listener pattern -- 16. Map a Sequence Based on Values
2017-11-11 [ES6] Extends class in ES6 vs ES5 subclass
2016-11-11 [Node.js] Testing ES6 Promises in Node.js using Mocha and Chai
2016-11-11 [Angular2] @Ngrx/store and @Ngrx/effects learning note
2015-11-11 [Javascript] Intro to the Web Audio API
2014-11-11 [Firebase] 4. Firebase Object related Database
点击右上角即可分享
微信分享提示