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)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Po_tta_tt0

콩심콩 팥심팥 🌱

✍ 공부/TypeScript

[type-challenges] Append to object

2023. 6. 27. 07:46
반응형

문제

주어진 인터페이스에 새로운 필드를 추가한 object 타입을 구현하세요. 이 타입은 세 개의 인자를 받습니다.

설명


/* _____________ Your Code Here _____________ */

type AppendToObject<T, U extends string | number | symbol, V> = {[P in keyof T | U]:P extends keyof T ? T[P] : V}

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


type test1 = {
  key: 'cat'
  value: 'green'
}

type testExpect1 = {
  key: 'cat'
  value: 'green'
  home: boolean
}

type test2 = {
  key: 'dog' | undefined
  value: 'white'
  sun: true
}

type testExpect2 = {
  key: 'dog' | undefined
  value: 'white'
  sun: true
  home: 1
}

type test3 = {
  key: 'cow'
  value: 'yellow'
  sun: false
}

type testExpect3 = {
  key: 'cow'
  value: 'yellow'
  sun: false
  moon: false | undefined
}

type cases = [
  Expect<Equal<AppendToObject<test1, 'home', boolean>, testExpect1>>,
  Expect<Equal<AppendToObject<test2, 'home', 1>, testExpect2>>,
  Expect<Equal<AppendToObject<test3, 'moon', false | undefined>, testExpect3>>,
]

너무 어려웠다
type AppendToObject<T, U extends string | number | symbol, V> = {[P in keyof T | U]:P extends keyof T ? T[P] : V}
하나하나 분석해보자

type AppendToObject<T, U, V> = {[P in keyof T | U]:P extends keyof T ? T[P] : V}
선수지식

  1. 타입스크립트 객체에 대한 지식 {[P in keyof T]:T[P]}가 타입 객체를 만든다는 것을 알면 된다!
  2. P extends T ? '통과시' : '실패시'는 P가 T를 포괄하는 타입 형태를 가질 때, 통과, 아니면 실패로 간다
  3. type AppendToObject<T, U extends string | number | symbol, V> = {[P in keyof T | U]:'안녕'}
    은
    type t = { home: "안녕"; key: "안녕"; value: "안녕"; }
    모양으로 만들어진다
    배열 내부에 유니온 타입으로 작성한 내용은, 순차적으로 하나씩 실행된다는 것!
  4. type TTT<T extends string | number | symbol,K extends string | number | symbol,P extends string | number | symbol> = {[R in T|K|P]:'하이'}
    type tt = TTT<'a','b','c'>
    type tt = { a: "하이"; b: "하이"; c: "하이"; } // 이렇게 나옵니다!

 

그럼 이제 문제에 들어가볼까요


type AppendToObject<T, U extends string | number | symbol, V> = {[P in keyof T | U]:P extends keyof T ? T[P] : V}


는, T,U,V를 받는데, U는 key로 기능해야 하기 때문에 string | number | symbol을 extends해줘야 합니다.

 

그리고 위에서 했던것과 마찬가지로,
keyof T(T 객체에 있는 key)와 U를 돌면서 P를 만들어줍니다


그리고 P가 keyof T를 extends 할 시 (= T에 들어있는 key일 시)
T[P](= T[key]의 value)
를 value로 주고,


그게 아닐 시(=U)
V를 value로 줍니다

 

 

 

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

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

[type-challenges] String to Union  (0) 2023.06.27
[type-challenges] Absolute  (0) 2023.06.27
[type-challenges] Flatten  (0) 2023.06.26
[type-challenges] Length of String  (0) 2023.06.26
[type-challenges] Append Argument  (0) 2023.06.26
    '✍ 공부/TypeScript' 카테고리의 다른 글
    • [type-challenges] String to Union
    • [type-challenges] Absolute
    • [type-challenges] Flatten
    • [type-challenges] Length of String
    Po_tta_tt0
    Po_tta_tt0
    감자의 코딩하는 블로그 콩심은데 콩나고 팥심은데 팥난다

    티스토리툴바