[Typescript] 33. Medium - Flatten

In this challenge, you would need to write a type that takes an array and emitted the flatten array type.

For example:

type flatten = Flatten<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, 5]

 

/* _____________ Your Code Here _____________ */

type Flatten<T extends any[]> = T extends [infer First, ...infer RT] 
    ? First extends any[]
      ? [...Flatten<First>, ...Flatten<RT>]
      : [First, ...Flatten<RT>]
    : [];

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

type cases = [
  Expect<Equal<Flatten<[]>, []>>,
  Expect<Equal<Flatten<[1, 2, 3, 4]>, [1, 2, 3, 4]>>,
  Expect<Equal<Flatten<[1, [2]]>, [1, 2]>>,
  Expect<Equal<Flatten<[1, 2, [3, 4], [[[5]]]]>, [1, 2, 3, 4, 5]>>,
  Expect<Equal<Flatten<[{ foo: 'bar'; 2: 10 }, 'foobar']>, [{ foo: 'bar'; 2: 10 }, 'foobar']>>,
]

 

posted @   Zhentiw  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-09-15 [CSS3] Use CSS Variables to Maintain the Aspect Ratio for an Element
2020-09-15 [GraphQL] Multi Query and Alias
2020-09-15 [Machine Learning] Gradient Checking
2019-09-15 [ARIA] What is Accessible Name Calculation?
2019-09-15 [ARIA] Accessible animations with reduced motion
2019-09-15 [ARIA] Accessible modal dialogs
2018-09-15 [Tools] Scroll, Zoom, and Highlight code in a mdx-deck slide presentation with Code Surfer <🏄/>
点击右上角即可分享
微信分享提示