Po_tta_tt0
콩심콩 팥심팥 🌱
Po_tta_tt0
전체 방문자
오늘
어제
  • 분류 전체보기 (266)
    • 🐛 회고 (14)
    • 💭 생각 (2)
    • 🤸‍♀️ 내 프로젝트 (16)
      • FISH-NEWS (8)
      • MBTI 과몰입 테스트 (2)
      • twitter clonecoding with TS (4)
      • pilzagenda (2)
    • 👨‍👩‍👧‍👦 팀 프로젝트 (2)
      • 피우다 프로젝트 (0)
      • SEMO(세상의 모든 모임) (1)
      • 마음을 전하는 텃밭 (1)
      • Stackticon (0)
    • 👨‍💻 CS지식 (11)
    • ✍ 공부 (94)
      • JavaScript (21)
      • TypeScript (39)
      • Html (0)
      • CSS (2)
      • React (18)
      • NextJS (7)
      • Vue (1)
      • Python (1)
      • Django (0)
      • 개발환경 & 그 외 (2)
    • 🏄‍♀️ 코딩테스트 (99)
      • 🐍 Python (99)
    • 🐙 Git & GitHub (3)
    • 📑 오류기록 (8)
    • 📚 우리를 위한 기록 (9)
    • 수업 (3)
    • 강의 등 (2)
    • 👩‍🎓 SSAFY (0)
    • 👋 우테코 (0)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

  • 문자열
  • Next.js
  • 파이썬
  • BFS + DP
  • DP
  • 이분탐색
  • react-router-dom
  • 플로이드 워셜
  • bfs
  • 파이썬 감시 피하기
  • 시뮬레이션
  • React
  • 백준
  • 백준 숨바꼭질
  • 자바스크립트
  • 백준 파이썬
  • 구현
  • 파이썬 다익스트라
  • js
  • dfs

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Po_tta_tt0

콩심콩 팥심팥 🌱

✍ 공부/TypeScript

[type-challenges] Pick

2023. 5. 16. 14:27
반응형

 

 

 

0. 문제

Pick<T,K>를 쓰지않고 타입 제어하기

type MyPick<T, K extends keyof T> = {
  [key in K] :T[key]
}

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'


type cases = [
  Expect<Equal<Expected1, MyPick<Todo, 'title'>>>,
  Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'>>>,
  // @ts-expect-error
  MyPick<Todo, 'title' | 'completed' | 'invalid'>,
]

interface Todo {
  title: string
  description: string
  completed: boolean
}

interface Expected1 {
  title: string
}

interface Expected2 {
  title: string
  completed: boolean
}

/* _____________ Further Steps _____________ */
/*
  > Share your solutions: https://tsch.js.org/4/answer
  > View solutions: https://tsch.js.org/4/solutions
  > More Challenges: https://tsch.js.org
*/

 

 

 

1. 설명

문제를 이해해보자.
MyPick type을 써서 Todo에 있는 title만 뽑아낸 타입을 만들고
MyPick type을 써서 Todo에 있는 title과 completed만 뽑아낸 타입을 만든다.
만약 Todo key에 없는 내용이 들어갔을 때 ('invalid') ts 에러를 발생시킨다.

type MyPick<T, K extends keyof T> = {
  [key in K] :T[key]
}

그러니까 여기서 MyPick은,

  • T(Todo)가 들어오고,
  • K extends keyof T(Todo의 key값으로 이루어진 K)를 받는 타입이다.
  • 이 후 key in K를 이용해 K가 'title'|'completed' 등 여러개를 pick 하는 상황을 고려한다. => key in K = title , key in K = completed 두개 다 통과한다
  • T[key]도 전과 마찬가지. T[title]: string, T[completed]: boolean이 되는 것.

 

 

추가 설명

1.

type name ='a' | 'b'
type TName = {[key in name]:string}

[key in name] : string
에 대해서 좀 더 알아보자

  • key in name -> 'a', 'b' 가 된다
  • 풀어서 말하면 {'a' : string, 'b' : string}이 되는 타입이 생성된 것
  • 결과적으로
    type TName = {
      a: string;
      b: string;
    }
    가 된다.

2.

Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'|'noname'>>>

이 예시는 어떻게 될까?
title과 completed는 Todo에 존재하지만, noname은 존재하지 않는다(invalid랑 같은 예시지만..😉)
따라서 typescript는

Type '"title" | "completed" | "noname"' does not satisfy the constraint 'keyof Todo'.
Type '"noname"' is not assignable to type 'keyof Todo'.

라는 에러를 발생시킨다.
typescript😣: keyof Todo에 왜 noname이 있는거야! Todo 안에 있는 key는 title이랑 completed밖에 없어야돼!!
라고 하는 격

반응형
저작자표시 (새창열림)

'✍ 공부 > TypeScript' 카테고리의 다른 글

[type-challenges] Length of Tuple  (0) 2023.05.23
[type-challenges] First of Array  (0) 2023.05.23
[type-challenges] Tuple to Object  (0) 2023.05.16
[type-challenges] Readonly  (0) 2023.05.16
[ 러닝 타입스크립트 ] 챕터 7. 인터페이스  (0) 2023.03.07
    '✍ 공부/TypeScript' 카테고리의 다른 글
    • [type-challenges] First of Array
    • [type-challenges] Tuple to Object
    • [type-challenges] Readonly
    • [ 러닝 타입스크립트 ] 챕터 7. 인터페이스
    Po_tta_tt0
    Po_tta_tt0
    감자의 코딩하는 블로그 콩심은데 콩나고 팥심은데 팥난다

    티스토리툴바