typescript - satisfies operator 탐구
typescript 4.9에서 새로 나온 기능으로 satisfies
라는 연산자가 있다.
공식문서를 정말 한참을 봤는데도 잘 이해가 가지 않았는데 직접 코드를 가지고 만져보니 조금 이해가 되었다.
satisfies 적용 전
Record
라는 객체의 key, value를 지정해주는 연산자를 사용하여 객체의 타입을 지정할 때,
아래 코드를 보면 value의 타입으로 string | RGB2
라는 union type으로 인해 속성에 대한 오류가 잡힌다.
toUpperCase에서는 only string
타입이 들어와야 하는데 union type으로 할당되어 생긴 에러로서 당연한 결과이다.
type Colors = 'red' | 'green' | 'blue';
type RGB = [red: number, green: number, blue: number];
const palette: Record<Colors, string | RGB2> = {
red: [255, 0, 0],
green: '#00ff00',
blue: [0, 0, 255],
};
const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();
// ^^^^^^^^^^^^^^
// error
// <html>TS2339: Property 'toUpperCase' does not exist on type 'string | RGB2'.<br/>Property 'toUpperCase' does not exist on type 'RGB2'.
마지막 코드의 palette.green.toUpperCase();
에서 green
부분을 호버해보면 다음과 같이 유니온 타입으 뜬다.
이런 경우를 위해 새로이 나온게 바로 satisfies
연산자인듯 싶다.
satisfies 적용
type을 똑같이 지정하고 객체에 대한 타입할당시 새 연산자를 사용하면 아래 예시와 같이 속성 연산에 있어서도 에러를 통과하게 된다.
즉, 유니온타입에서도 일부 유형을 만족한다면 해당 타입으로 추론하여 통과하게 되는듯 하다.
type Colors = 'red' | 'green' | 'blue';
type RGB = [red: number, green: number, blue: number];
const palette = {
red: [255, 0, 0],
green: '#00ff00',
blue: [0, 0, 255],
} satisfies Record<Colors, string | RGB>;
const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();
// OK!!
위와 마찬가지로 palette.green.toUpperCase()
에서 green
부분을 호버해보면 유니온 타입이 아닌 string
으로 할당되어 있음을 볼 수 있다.
객체가 아닌 경우의 유니온 타입에서도 될까 하고 몇가지 실험을 해봤는데 기본적으로 일단은 객체에서만 작동하는 듯 하다.
객체를 주로 사용하는 entities 모델에서도 잘 작동되는지 확인 후, 이상 없다면 굉장히 유용하게 쓰일 듯 싶다.