Go Back
Refer: Easy - Push
Describe
Implement the generic version of Array.push
For example
code snippetCopytypescripttype Result = Push<[1, 2], '3'> // [1, 2, '3']
Test Cases
code snippetCopytypescriptimport { Equal, Expect, ExpectFalse, NotEqual } from '@type-challenges/utils'
type cases = [
Expect<Equal<Push<[], 1>, [1]>>,
Expect<Equal<Push<[1, 2], '3'>, [1, 2, '3']>>,
Expect<Equal<Push<['1', 2, '3'], boolean>, ['1', 2, '3', boolean]>>,
Expect<Equal<Push<['1', 2, '3'], '3'>, ['1', 2, '3']>>,
]
Solution
Question: Push<['1', 2, '3'], '3'>
why not equal to ['1', 2, '3', '3']
in Push operation?
It fixed in #7947.
code snippetCopytypescript// my solution
type Push<T extends any[], U> = T['length'] extends 0
? [U]
: T extends [...infer P, infer K]
? K extends U
? T
: [...T, U]
: never
// other solutions
type Push<T extends any[], U> = [U] extends [T[number]] ? T : [...T, U]
The reason of wrapped U
and T[number]
is refer to here.