Unshift
介绍
实现Array.unshift
类型版本
For example
typescript
type Result = Unshift<[1, 2], 0>; // [0, 1, 2,]
View on GitHubtypescript
type Result = Unshift<[1, 2], 0>; // [0, 1, 2,]
起点
ts
/* _____________ Your Code Here _____________ */typeUnshift <T ,U > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Unshift <[], 1>, [1]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Unshift <[1, 2], 0>, [0, 1, 2]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Unshift <['1', 2, '3'], boolean>, [boolean, '1', 2, '3']>>];
take the challengets
/* _____________ Your Code Here _____________ */typeUnshift <T ,U > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Unshift <[], 1>, [1]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Unshift <[1, 2], 0>, [0, 1, 2]>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Unshift <['1', 2, '3'], boolean>, [boolean, '1', 2, '3']>>];
解决方案
Spoiler warning // Click to reveal answer
ts
// 方案1typeUnshift <T ,U > =T extends unknown[] ? [U , ...T ] : never
ts
// 方案1typeUnshift <T ,U > =T extends unknown[] ? [U , ...T ] : never
ts
// 方案2typeUnshift <T ,U > =T extends [...inferRest ] ? [U , ...Rest ] : never;
ts
// 方案2typeUnshift <T ,U > =T extends [...inferRest ] ? [U , ...Rest ] : never;