yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00012-medium-last #12

Open yunliuyan opened 11 months ago

yunliuyan commented 11 months ago

最后一个元素 中等 #array

by Anthony Fu @antfu

接受挑战    English 日本語

由谷歌自动翻译,欢迎 PR 改进翻译质量。

在此挑战中建议使用TypeScript 4.0

实现一个通用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

测试案例

import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Last<[3, 2, 1]>, 1>>,
  Expect<Equal<Last<[() => 123, { a: string }]>, { a: string }>>,
]

返回首页 分享你的解答 查看解答

相关挑战

14・第一个元素 16・出堆
yunliuyan commented 11 months ago

思路

获取最后一位数的index,如果获取最后的index,通过infer

代码实现

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

type LastIndex<T extends readonly any[]> = T extends [infer U, ...infer args] ? args['length'] : never

type Last<T extends readonly  any[]> = T[LastIndex<T>]

type tail1 = Last<arr1> // expected to be 'c'
type tail2 = Last<arr2> // expected to be 1
Janice-Fan commented 11 months ago
type Last<T extends unknown[]> = T extends [...unknown[], infer P] ? P : never;

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
liangchengv commented 11 months ago
type Last<T extends unknown[]> = T extends [...infer U, infer K] ? K : never;

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
wudu8 commented 11 months ago
type LastIndex<T extends readonly any[]> = T extends [infer U, ...infer args] ? args['length'] : never
type MyEasyLast<T extends any[]> = T[LastIndex<T>];

const easyLastFun = () => 1;
type easyLastArr1 = ["2", 3, true, "a"];
type easyLastArr2 = ["2", 3, true, 2];
type easyLastArr3 = ["2", 3, true, false];
type easyLastArr4 = ["2", 3, true, true];
type easyLastArr5 = ["2", 3, true, typeof easyLastFun];

type easyLastTest1 = MyEasyLast<easyLastArr1>; // expected to be 'a'
type easyLastTest2 = MyEasyLast<easyLastArr2>; // expected to be 2
type easyLastTest3 = MyEasyLast<easyLastArr3>; // expected to be false
type easyLastTest4 = MyEasyLast<easyLastArr4>; // expected to be true
type easyLastTest5 = MyEasyLast<easyLastArr5>; // expected to be () => number
type easyLastTest7 = MyEasyLast<["2", 3, true, "a"]>; // expected to be 'a'
type easyLastTest8 = MyEasyLast<["2", 3, true, () => number]>; // expected to be () => number
Naparte commented 11 months ago

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

type Last<T> = T extends [...infer arr, infer lastItem] ? lastItem : never;

type arr110 = ['a', 'b', 'c']
type arr210 = [3, 2, 1]

type tail1 = Last<arr110> // expected to be 'c'
type tail2 = Last<arr210> // expected to be 1