타입스크립트 4.9버전부터 새롭게 등장한 연산자가 있습니다. 바로 Satisfies인데요. 해당 연산자를 통해 타입 가드를 이용하지 않고 더 간단하게 개발을 할 수 있습니다.
Documentation - TypeScript 4.9
TypeScript 4.9 Release Notes
www.typescriptlang.org
Satisfies란?
satisfies는 타입을 명시적으로 선언하는 행위 대신해서 사용할 수 있는 방법입니다. 이때 명시적인 타입 선언과 다른점은 알아서 타입 가드처럼 validating 과정을 거쳐준다는 것입니다. 아래 예시를 통해 설명하겠습니다.
type LocationValue = LocationName | LocationCoordinate;
type LocationName = 'seoul' | 'suwon';
type LocationCoordinate = {
x: number,
y: number
};
type Building = {
size: number,
location: LocationValue
}
///////////////////////// 기존 방식 ////////////////////////////
const building_1 : Building = {
size: 13,
location: 'seoul'
}
// ⚠️ 에러 발생. 에러 내용은 다음과 같음
// Property 'length' does not exist on type 'LocationValue'.
// Property 'length' does not exist on type 'LocationCoordinate'.
console.log(building_1.location.length);
// ⚠️ 해결 방법 : 타입 가드
if (typeof building_1.location === 'string') {
console.log(building_1.location.length);
}
///////////////////////// Satisfies 방식 ////////////////////////////
const building_2 = {
size: 13,
location: 'seoul'
} satisfies Building
// ✅ 에러 발생하지 않음
console.log(building_2.location.length);
위 예시를 보면 알 수 있듯 기존의 명시적인 타입 선언 방식에서 문제가 발생하는 경우가 있습니다. 설정된 내용을 보면 building_1.location에 해당하는 타입은 LocationValue으로 LocationName, LocationCoordinate로 이루어진 유니온 타입입니다. 이때 LocationName은 'seoul'과 'suwon'이라는 리터럴 타입을 사용하기에 length 속성이 존재하지만, LocationCoordinate에는 length 속성이 없습니다. 그러기에 에러가 발생합니다.( Property 'length' does not exist on type 'LocationValue'. )
이를 해결하기 위해서는 타입 가드를 이용해 원하는 타입으로 범위를 좁혀줘야합니다. 그럼 위와 같은 에러를 해결할 수 있습니다.
이때 이런 방법을 더 쉽게 해결하기 위해 추가된 연산자가 바로 'satisfies' 입니다. satisfies는 building_2 변수를 선언 및 초기화하는 과정에 사용되었습니다. 이를 통해 building_2의 key값 중 location이 단순 LocationName | LocationCoordinate로 추론되지 않고 LocationName임을 확실히 알 수 있습니다. 그렇기에 length는 위처럼 LocationName('seoul' | 'suwon') 에서 문제가 되지 않는 속성이므로 에러가 사라집니다.
'백엔드 > Node.js' 카테고리의 다른 글
[TS] 타입스크립트 추론 종류 - 타입 추론(Type Inference) / 리터럴 추론(Literal Inference) (0) | 2025.04.14 |
---|---|
[TS] 타입스크립트 type vs interface 차이? (0) | 2025.04.14 |
[TS] 타입 체킹 - 덕 타이핑(Duck Typing, Structural SubTyping)이란? (0) | 2025.04.09 |
[TS] 타입가드(Type Guard)란? (0) | 2025.04.09 |
[TS] 타입 단언(Type Assertion)이란? (0) | 2025.04.09 |