Typescript类型体操 - Reverse

题目

中文

实现类型版本的数组反转 Array.reverse

例如:

type a = Reverse<['a', 'b']>; // ['b', 'a']
type b = Reverse<['a', 'b', 'c']>; // ['c', 'b', 'a']

English

Implement the type version of Array.reverse

For example:

type a = Reverse<['a', 'b']>; // ['b', 'a']
type b = Reverse<['a', 'b', 'c']>; // ['c', 'b', 'a']

答案

type Reverse<T extends any[]> = T extends [infer L, ...infer R]
    ? [...Reverse<R>, L]
    : T;

在线演示

posted @ 2022-09-23 00:38  Laggage  阅读(51)  评论(0编辑  收藏  举报