lxxmnmn / type-challenges

TypeScript type challenges
https://tsch.js.org/
MIT License
0 stars 0 forks source link

18 - Length of Tuple #6

Open lxxmnmn opened 1 month ago

lxxmnmn commented 1 month ago

Length of Tuple easy #tuple

배열(튜플)을 받아 길이를 반환하는 제네릭 Length<T>를 구현하세요.

/* _____________ Your Code Here _____________ */

type Length<T extends readonly any[]> = T['length'];
/* _____________ Test Cases _____________ */

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

const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const
const spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'] as const

type cases = [
  Expect<Equal<Length<typeof tesla>, 4>>,
  Expect<Equal<Length<typeof spaceX>, 5>>,
  // @ts-expect-error
  Length<5>,
  // @ts-expect-error
  Length<'hello world'>,
]
lxxmnmn commented 1 month ago

TypeScript에서 배열의 길이를 타입으로 얻기

T['length']는 배열 타입 T의 길이를 타입으로 나타냄

type MyTuple = [number, string, boolean];
type Length = MyTuple['length']; // 3