Typescript - satiesfies 연산자

00_8_3·2023년 4월 5일
0

typescript

목록 보기
2/8

TS4.9 - satiesfies

  • 타입 선언
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'.
  • satiesfies
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 연산자의 경우 객체 리터럴의 실제 타입이 변수의 타입으로 사용되어 키와 값에 대한 정보가 보존됩니다.

nested object

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

타입선언과 satiesfies 같이 사용하면?

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
  • satiesfies가 타입 선언에 덮어씌어 진다.

as const satiesfies

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) 

참고

0개의 댓글