type Colors = "red" | "green" | "blue";
const favoriteColors: Record<Colors, unknown> = {
"red": "yes",
"green": false,
"blue": "kinda",
};
favoriteColors.blue.toUpperCase() // 'favoriteColors.blue' is of type 'unknown'.
favoriteColors.green.toUpperCase() // 'favoriteColors.green' is of type 'unknown'.
type Colors = "red" | "green" | "blue";
const favoriteColors = {
"red": "yes",
"green": false,
"blue": "kinda",
} as Record<Colors, unknown>;
favoriteColors.blue.toUpperCase() // 'favoriteColors.blue' is of type 'unknown'.
favoriteColors.green.toUpperCase() // 'favoriteColors.green' is of type 'unknown'.
type Colors = "red" | "green" | "blue";
const favoriteColors = {
"red": "yes",
"green": false,
"blue": "kinda",
} satisfies Record<Colors, unknown>;
favoriteColors.blue.toUpperCase() // ok, it's a string
favoriteColors.green.toUpperCase() // error, it's a boolean
타입 선언과 타입 단언의 경우 원본 객체 리터럴의 타입이 덧씌어지는데 비해
satiesfies
연산자의 경우 객체 리터럴의 실제 타입이 변수의 타입으로 사용되어 키와 값에 대한 정보가 보존됩니다.
const a = {
b: {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255]
} satisfies Record<Colors, string | RGB>,
c: "asdf",
d: {
red: "test",
green: 1
} satisfies Record<"red" | "green", string | number>
}
const b = a.b.red // [number, number, number]
const c= a.d.red // string
const a: {b: Record<Colors, string | RGB>, c: string, d: Record<"red" | "green", string | number>} = {
b: {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255]
} satisfies Record<Colors, string | RGB>,
c: "asdf",
d: {
red: "test",
green: 1
}
}
const b = a.b.red // const b: string | RGB
const c= a.d.red // const c: string | number
type Route = { path: string; children?: Routes }
type Routes = Record<string, Route>
function navigate(path: '/' | '/auth') {
// 로직
}
const routes = {
HOME: { path: '/' }
} satisfies Routes
navigate(routes.HOME.path)
Argument of type 'string' is not assignable to parameter of type '"/" | "/auth"'
에러 발생.
as const
를 사용하여 타입 narrow로 해결 할 수 있다.
type Route = { path: string; children?: Routes }
type Routes = Record<string, Route>
function navigate(path: '/' | '/auth') {
// 로직
}
const routes = {
HOME: { path: '/' }
} as const satisfies Routes
navigate(routes.HOME.path)