Skip to main content

Push

introduction#

Implement the generic version of Array.push

For example

typescript
type Result = Push<[1, 2], '3'>; // [1, 2, '3']
typescript
type Result = Push<[1, 2], '3'>; // [1, 2, '3']
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type Push<T, U> = any;
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<Push<[], 1>, [1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Push<[1, 2], '3'>, [1, 2, '3']>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Push<['1', 2, '3'], boolean>, ['1', 2, '3', boolean]>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
ts
/* _____________ Your Code Here _____________ */
type Push<T, U> = any;
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<Push<[], 1>, [1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Push<[1, 2], '3'>, [1, 2, '3']>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Push<['1', 2, '3'], boolean>, ['1', 2, '3', boolean]>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
take the challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type Push<T, U> = T extends [...infer Items] ? [...Items, U] : never;
Try
ts
type Push<T, U> = T extends [...infer Items] ? [...Items, U] : never;
Try
view more solutions