Typescript類型體操 - IsTuple

題目

中文

實現 IsTuple 類型, 接受一個泛型參數 T 作爲輸入, 並返回 T 是否爲 tuple 類型

示例:

type case1 = IsTuple<[number]>; // true
type case2 = IsTuple<readonly [number]>; // true
type case3 = IsTuple<number[]>; // false

English

Implement a type IsTuple, which takes an input type T and returns whether T is tuple type.

For example:

type case1 = IsTuple<[number]>; // true
type case2 = IsTuple<readonly [number]>; // true
type case3 = IsTuple<number[]>; // false

答案

/**
 * 元組的長度是有限的,其`length`屬性返回的是數字字面量;數組的`length`屬性的類型是`number`
 */
type IsTuple<T> = [T] extends [never]
    ? false
    : T extends readonly any[]
    ? number extends T['length']
        ? false
        : true
    : false;

在線演示

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