题目

创建一个通用的 Length,接受一个 readonly 的数组,返回这个数组的长度。

  1. type tesla = ['tesla', 'model 3', 'model X', 'model Y']
  2. type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']
  3. type teslaLength = Length<tesla> // expected 4
  4. type spaceXLength = Length<spaceX> // expected 5

单元测试

  1. import { Equal, Expect } from '@type-challenges/utils'
  2. const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const
  3. const spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'] as const
  4. type cases = [
  5. Expect<Equal<Length<typeof tesla>, 4>>,
  6. Expect<Equal<Length<typeof spaceX>, 5>>,
  7. // @ts-expect-error
  8. Length<5>,
  9. // @ts-expect-error
  10. Length<'hello world'>,
  11. ]import { Equal, Expect } from '@type-challenges/utils'
  12. type cases = [
  13. Expect<Equal<First<[3, 2, 1]>, 3>>,
  14. Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
  15. Expect<Equal<First<[]>, never>>,
  16. Expect<Equal<First<[undefined]>, undefined>>
  17. ]

通过 JS 解题

  1. function getLength (arr) {
  2. if(!Array.isArray(arr)) return;
  3. return arr.length;
  4. }

知识点

  1. 什么是 tuple 类型
  2. tuple 和普通的数组有什么区别
    类型定死,长度定长的数组,
    取 tuple 的 length 是一个定值,普通数组是一个 number 类型

    翻译为 TS

    1. type Length<T extends readonly any[]> = T["length"];