Push
介绍
实现常规版本的Array.push
例如:
typescript
type Result = Push<[1, 2], '3'>; // [1, 2, '3']
View on GitHubtypescript
type Result = Push<[1, 2], '3'>; // [1, 2, '3']
起点
ts
/* _____________ Your Code Here _____________ */typePush <T ,U > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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]>>];
take the challengets
/* _____________ Your Code Here _____________ */typePush <T ,U > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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]>>];
解决方案
Spoiler warning // Click to reveal answer
ts
// 方案1// type Push<T extends any[], U> = T['length'] extends 0 ? [U] : [...T,U];typePush <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];typePush <T extends any[],U > = [...T ,U ];/*** 方案1虽然通过了了测试,但是有潜在问题. 体现在:* 1) 类型合并 如果U的类型和已有类型重叠, TS可能会合并类型 Push<[string], string>* 2) 只读元组 因为T extends any[]的约束拒绝读取只读元组*/
ts
// 方案2typePush <T extends unknown[],U > = [...T ,U ];/*** 接受只读数组,允许普通数组, 非数组报错*/
ts
// 方案2typePush <T extends unknown[],U > = [...T ,U ];/*** 接受只读数组,允许普通数组, 非数组报错*/
ts
// 方案3typePush <T ,U > =T extends [...inferItems ] ? [...Items ,U ] : never;
ts
// 方案3typePush <T ,U > =T extends [...inferItems ] ? [...Items ,U ] : never;