ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
470 stars 56 forks source link

type-challenges-solutions/en/medium-pop #28

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Pop

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-pop.html

dvlden commented 3 years ago

Following the previous exercise that I did not understand (and I still don't), here's my solution and extras from the same challenge, that were optional.

type Pop<T extends unknown[]> = T extends [...infer L, unknown] ? L : never
type Push<T extends unknown[], V> = [...T, V]
type Shift<T extends unknown[]> = T extends [unknown, ...infer F] ? F : never
type Unshift<T extends unknown[], V> = [V, ...T]

Test cases:

type cases = [
  Expect<Equal<Pop<[3, 2, 1]>, [3, 2]>>,
  Expect<Equal<Pop<['a', 'b', 'c', 'd']>, ['a', 'b', 'c']>>,

  Expect<Equal<Push<[1, 2, 3], 4>, [1, 2, 3, 4]>>,
  Expect<Equal<Push<['a', 'b', 'c'], 'd'>, ['a', 'b', 'c', 'd']>>,

  Expect<Equal<Shift<[1, 2, 3]>, [2, 3]>>,
  Expect<Equal<Shift<['a', 'b', 'c', 'd']>, ['b', 'c', 'd']>>,

  Expect<Equal<Unshift<[1, 2, 3], 4>, [4, 1, 2, 3]>>,
  Expect<Equal<Unshift<['a', 'b', 'c', 'd'], 'e'>, ['e', 'a', 'b', 'c', 'd']>>,
]
ghaiklor commented 3 years ago

@dvlden you mean the explanation is unclear? Please, ask follow-up questions and we try to improve the content.

MajorLift commented 1 year ago

Update for new test case.

Expect<Equal<Pop<[]>, []>>
type Pop<T extends any[]> = T["length"] extends 0 ? [] : T extends [...infer H, infer T] ? H : never
MajorLift commented 1 year ago

Alternatively,

type Pop<T extends any[]> = T extends [...infer H, infer _] ? H : []