跳到主要内容

Push

介绍

实现常规版本的Array.push

例如:

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

起点

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'.
];
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'.
];
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
 
// 方案1
// type Push<T extends any[], U> = T['length'] extends 0 ? [U] : [...T,U];
type Push<T extends any[], U> = [...T, U];
/**
* 方案1虽然通过了了测试,但是有潜在问题. 体现在:
* 1) 类型合并 如果U的类型和已有类型重叠, TS可能会合并类型 Push<[string], string>
* 2) 只读元组 因为T extends any[]的约束拒绝读取只读元组
*/
ts
 
// 方案1
// type Push<T extends any[], U> = T['length'] extends 0 ? [U] : [...T,U];
type Push<T extends any[], U> = [...T, U];
/**
* 方案1虽然通过了了测试,但是有潜在问题. 体现在:
* 1) 类型合并 如果U的类型和已有类型重叠, TS可能会合并类型 Push<[string], string>
* 2) 只读元组 因为T extends any[]的约束拒绝读取只读元组
*/
ts
// 方案2
type Push<T extends unknown[], U> = [...T, U];
/**
* 接受只读数组,允许普通数组, 非数组报错
*/
 
ts
// 方案2
type Push<T extends unknown[], U> = [...T, U];
/**
* 接受只读数组,允许普通数组, 非数组报错
*/
 
ts
// 方案3
type Push<T,U> = T extends [...infer Items] ? [...Items, U] : never;
ts
// 方案3
type Push<T,U> = T extends [...infer Items] ? [...Items, U] : never;
view more solutions