Type-Challenges_1 (warm-up ~ easy 1 / 2)

타입스크립트 관련 재밌는 Challenge 발견!! 🤔
난이도는 warm-up, easy, medium, hard, extreme 총 5단계로 나뉘어져있고
하나씩 진행하며 글 남겨보려 합니다..!!
참고자료 및 출처 👉 챌린지 사이트

warm-up

13 - Hello World

// qs
type HelloWord = any
// answer
type HelloWord = string

easy

4 - Pick

// qs
type MyPick<T, K> = any
// answer
type MyPick<T, K extends keyof T> = {
  [P in K]: T[P]
}
// test-case
interface Todo {
  title: string
  description: string
  completed: boolean
}
type TodoPreview = MyPick<Todo, 'title' | 'completed'>
const todo: TodoPreview = {
    title: 'Clean room',
    completed: false,
}

7 - Readonly

// qs
type MyReadonly<T> = any
// answer
type MyReadonly<T> = {
  readonly [K in keyof T]: T[K]
}
// test-case
interface Todo {
  title: string
  description: string
}
const todo: MyReadonly<Todo> = {
  title: "Hey",
  description: "foobar"
}
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property

11 - Tuple to Object

// qs
type TupleToObject<T extends readonly any[]> = any
// answer
type TupleToObject<T extends readonly string[]> = {
  [K in T[number]]: K
}
// test-case
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}

14 - First of Array

// qs
type First<T extends any[]> = any
// answer
type First<T extends any[]> = T extends [] ? never : T[0]
// test-case
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3

18 - Length of Tuple

// qs
type Length<T extends any> = any
// answer
type Length<T extends readonly string[]> = T['length']
// test-case
type tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const;
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'] as const;
type teslaLength = Length<tesla>  // expected 4
type spaceXLength = Length<spaceX> // expected 5

43 - Exclude

// qs
type MyExclude<T, U> = any
// answer
type MyExclude<T, U> = T extends U ? never : T
// test-case
type T0 = MyExclude<"a" | "b" | "c", "a"> // expected "b" | "c"
type T1 = MyExclude<"a" | "b" | "c", "a" | "b"> // expected "c"
type T2 = MyExclude<string | number | (() => void), Function> // expected string | number

좋은 웹페이지 즐겨찾기