object의 key 값만 가져오고 싶을 때
값을 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",
};
type Inventory = {
[key in Car]?: string
}
이런 식을 작성하면, Car enum이 숫자형 enum 이기때문에 key 들이 0, 1, 2 로 나온다.
as const가 있으면 고정된 값으로 타입을 지정해준다.
const obj2 = { a: "123", b: "hello", c: "world" } as const;
type Key2 = typeof obj2[keyof typeof obj2]; // "123" | "hello" | "world"
자바스크립트에서 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() };
}, {});
}