프로그래밍/JS, Node.js

[TypeScript] satisfies 연산자 알아보기

Lou Park 2023. 1. 24. 20:34

satisfies operator

satisfies는 TypeScript 4.9 버전 부터 새롭게 추가된 연산자로, 업캐스팅(up-casting)으로 Type-safety를 보장한다.

💡 업캐스팅?
부모 - 자식 상속관계의 클래스가 있을때 부모 → 자식 방향의 형변환을 다운캐스팅, 자식 → 부모 방향의 형변환을 업캐스팅이라 한다.


Parent p = new Parent();
Child c = new Child();
Parent p2 = (Parent) c; // 업캐스팅
Child c2 = (Child) p2; // 다운캐스팅

Typescript의 경우 한 타입이 다른 타입의 값을 모두 포함하고 있으면 상속관계가 된다.

업캐스팅과 다운캐스팅

사용 예시를 바로 보자. VersionsVersionRecordsatifsfies 한다고 선언했다.

export type Version = {
is_force_update: boolean;
use_legacy_update: boolean;
update_version_code: number;
settings_version_code: number;
update_message?: string;
}
export type VersionRecord = Record<string, Version>
const Versions = {
PRD: {
is_force_update: false,
use_legacy_update: true,
update_version_code: 564,
settings_version_code: 566,
},
} satisfies VersionRecord

 

장점만 빠르게

타입에 정의되어 있지 않은 Property 추가: ❌ 불가능

Version type에 정의되어있지 않은 Property를 추가하려할때 IDE는 에러를 보여준다.

 

존재하지 않는 Property에 대한 접근: ❌ 불가능

satisfies를 사용했을 경우 Versions에 있는 모든 property를 추론 가능하게 해준다. 그래서 존재하지 않는 property에 접근하려할 경우 IDE는 에러를 보여준다. 이는 오타나 예기치 못한 값에 접근하는 상황을 방지한다.

const isForceUpdate = Versions.HEHEHE.is_force_update // ❌ Property 'HEHEHE' does not exist on type

 

타입을 명시하면요?

타입에 정의되어 있지 않은 Property 추가: ❌ 불가능

const Versions: VersionRecord = {
PRD: {
is_force_update: false,
use_legacy_update: true,
update_version_code: 564,
settings_version_code: 566,
hehehehe: 2333 // 'hehehe' does not exist in type 'Version'.
},
}

 

존재하지 않는 Property에 대한 접근:가능

const isForceUpdate = Versions.HEHEHE.is_force_update // ✅ No problem

 

as 키워드를 사용하면요?

as 키워드는 *다운캐스팅이다.

타입에 정의되어 있지 않은 Property 추가: ✅ 가능

존재하지 않는 Property에 대한 접근: ✅ 가능

const Versions = {
PRD: {
is_force_update: false,
use_legacy_update: true,
update_version_code: 564,
settings_version_code: 566,
hehehehe: 2333 // ✅ No problem
},
} as VersionRecord
const isForceUpdate = Versions.HEHEHE.is_force_update // ✅ No problem