Typescript类型体操 - Last of Array

题目

中文

实现一个通用Last<T>,它接受一个数组T并返回其最后一个元素的类型。

例如

type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]

type tail1 = Last<arr1> // expected to be 'c'
type tail2 = Last<arr2> // expected to be 1

English

Implement a generic Last<T> that takes an Array T and returns its last element.

For example

type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]

type tail1 = Last<arr1> // expected to be 'c'
type tail2 = Last<arr2> // expected to be 1

答案

type Last<T extends any[]> = T extends [infer L, ...infer R] ? (R['length'] extends 0 ? L : Last<R>) : never;

在线演示

posted @ 2022-09-04 21:56  Laggage  阅读(34)  评论(0编辑  收藏  举报