Typescript类型体操 - Unique

题目

中文

实现类型的 Lodash.uniq, Unique 接受数组 T, 返回没有重复值的数组 T

English

Implement the type version of Lodash.uniq, Unique takes an Array T, returns the Array T without repeated values.

type Res = Unique<[1, 1, 2, 2, 3, 3]>; // expected to be [1, 2, 3]
type Res1 = Unique<[1, 2, 3, 4, 4, 5, 6, 7]>; // expected to be [1, 2, 3, 4, 5, 6, 7]
type Res2 = Unique<[1, 'a', 2, 'b', 2, 'a']>; // expected to be [1, "a", 2, "b"]
type Res3 = Unique<[string, number, 1, 'a', 1, string, 2, 'b', 2, number]>; // expected to be [string, number, 1, "a", 2, "b"]
type Res4 = Unique<[unknown, unknown, any, any, never, never]>; // expected to be [unknown, any, never]

答案

type Contains<TArr extends any[], T> = TArr extends [infer L, ...infer R]
    ? (<F>() => F extends L ? 1 : 0) extends <F>() => F extends T ? 1 : 0
        ? true
        : Contains<R, T>
    : false;

type Unique<T extends any[], O extends any[] = []> = T extends [
    infer L,
    ...infer R
]
    ? Contains<O, L> extends true
        ? Unique<R, O>
        : [L, ...Unique<R, [...O, L]>]
    : [];

这题的主要问题和 05317-medium-lastindexof 一样, 就是判断两个类型是否完全相同, type-challenge-last-index-of; 这个问题解决了剩下的就是简单的递归了

在线演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章