내배캠 78일차

·2023년 1월 30일
0

내일배움캠프

목록 보기
85/142
post-thumbnail

사용한 git hub 주소

타입추론

keyof

object의 key 값만 가져오고 싶을 때

typeof

값을 type으로 쓰고 싶을 때

enum Color {
  Red,
  Blue,
  Black,
}

enum Car {
  Sedan,
  Truck,
  Coupe,
}

type Inventory = {
  [CarName in keyof typeof Car]?: keyof typeof Color;
};

const inventory: Inventory = {
  Sedan: "Red",
  Truck: "Black",
};

keyof typeof 사용한 이유

type Inventory = {
	[key in Car]?: string
}

이런 식을 작성하면, Car enum이 숫자형 enum 이기때문에 key 들이 0, 1, 2 로 나온다.

추가)as const

as const가 있으면 고정된 값으로 타입을 지정해준다.

const obj2 = { a: "123", b: "hello", c: "world" } as const;
type Key2 = typeof obj2[keyof typeof obj2]; // "123" | "hello" | "world"
  • as const가 있을 때: { a: '123', b: 'hello', c: 'world' }
  • as const가 없을 때: { a: string, b: string, c: string } 이 경우 type Key2은 string이 된다.

Array.reduce()로 배열을 객체로 변환

자바스크립트에서 Array의 reduce()는 배열의 모든 요소들에 대해서 각각 연산을 수행하여 하나의 결과 값을 계산하는 함수!

enum Status {
  Initialized = "Initialized",
  Pending = "Pending",
  Complete = "Complete",
}

type StatusObject = { [key in Status]?: string };

export function getStatusObject(): StatusObject {
  return Object.keys(Status).reduce((result, status) => {
    return { ...result, [status]: status.toLowerCase() };
  }, {});
}
  1. result : 누적된 계산값, 현재 시작값을 {}로 지정해둠!
  2. result에 [status]: status.toLowerCase()를 반복해서 넣어줌!
    • 첫번째 : { ...{} , ["Initialized"] : "initialized"}
      => result : {Initialized: "initialized"}
    • 두번째 : { ... {Initialized: "initialized"}, ["Pending" ] : "pending" }
      => result : {Initialized: "initialized", "Pending" : "pending"}
    • 세번째 : { ... {Initialized: "initialized", "Pending" : "pending"}, ["Complete" ] : "complete" }
      => result : {Initialized: "initialized", Pending : "pending", Complete : "complete"}
  3. return result

참고

profile
개발자 꿈나무

0개의 댓글