[Typescript] 67. Medium - Chunk
typescript Medium 67 chunk
2023-09-14 09:00:44 时间
Do you know lodash
? Chunk
is a very useful function in it, now let's implement it. Chunk<T, N>
accepts two required type parameters, the T
must be a tuple
, and the N
must be an integer >=1
type exp1 = Chunk<[1, 2, 3], 2> // expected to be [[1, 2], [3]] type exp2 = Chunk<[1, 2, 3], 4> // expected to be [[1, 2, 3]] type exp3 = Chunk<[1, 2, 3], 1> // expected to be [[1], [2], [3]]
/* _____________ Your Code Here _____________ */ type Chunk<T extends any[], U extends number, ACC extends any[]= []> = ACC['length'] extends U ? [ACC, ...Chunk<T, U>] : T extends [infer F, ...infer RT] ? Chunk<RT, U, [...ACC, F]> : ACC['length'] extends 0 ? [] : [ACC]; /* _____________ Test Cases _____________ */ import type { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<Chunk<[], 1>, []>>, Expect<Equal<Chunk<[1, 2, 3], 1>, [[1], [2], [3]]>>, Expect<Equal<Chunk<[1, 2, 3], 2>, [[1, 2], [3]]>>, Expect<Equal<Chunk<[1, 2, 3, 4], 2>, [[1, 2], [3, 4]]>>, Expect<Equal<Chunk<[1, 2, 3, 4], 5>, [[1, 2, 3, 4]]>>, Expect<Equal<Chunk<[1, true, 2, false], 2>, [[1, true], [2, false]]>>, ]
相关文章
- [Typescript] 136. Medium - NonEmptyArray
- [Typescript] Tips: Throw detailed error messages for type checks
- [Typescript] 43. Medium - Percentage Parser
- [Typescript] 33. Medium - Flatten
- [Typescript challenge] 19. Medium - Tuple to Union
- [Typescript] 23. Medium - Promise.all
- [Typescript] 11. Medium - Equal
- [Typescript] Scopes and TypeParams
- [TypeScript] Variadic Tuple Types V4 ...T
- [Typescript] Dynamic types: Use TypeScript's Mapped Types and Template Literal Types Together
- [Typescript] Configuration Inheritance with Extends
- [Typescript] 132. Medium - Filter
- [Typescript] 98. Medium - Append to object
- [Typescript] 95. Hard - Required Keys
- [Typescript] 90. Medium - Replace
- [Typescript] 51. Medium - Mutable
- [Typescript] 25. Medium - Trim Left
- [Typescript] 23. Medium - Promise.all
- [Typescript] Dynamic types: Use TypeScript's Mapped Types and Template Literal Types Together
- [TypeScript] Statically Type String Literals with Template Literal Types in TypeScript
- [Typescript] Create Type From Any Given Data in TypeScript
- [Typescript] Emitting Declaration Files
- typescript ts定义对象类型的三种方式
- 在 TypeScript 中,{},object 和 Object 表示三个不同的类型,它们的区别和用途