https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
satisfies는 4.9 버전에 추가된 operator
type Shape = {
type: 'oval' | 'rect';
color: string | number;
}
const shape: Shape = {
type: 'rect',
color: 1
}
typeof shape = {
type: 'oval' | 'rect';
color: string | number;
}
위의 예제에서 볼 수 있듯이 shape의 타입은 Shape과 동일하게 설정된다.
이 말은 즉, color에 number 타입의 값을 지정했음에도 불구하고 string | number로 추론된다는 것이다.
때문에 shape.color에 사용할 수 있는 프로퍼티는 string과 number 모두에 공통적으로 존재하는 3개이다.
하지만 당연히 color 값에 number 타입을 지정했기 때문에, number 타입에서 사용할 수 있는 모든 프로퍼티에 접근하고자 하는 니즈가 생길 수 있다
이러한 니즈를 충족하기 위해 만들어진 기능이 satisfies이다.
const shape2 = {
type: 'rect',
color: 1
} satisfies Shape
typeof shape2 = {
type: 'rect';
color: number;
}
const shape3 = {
type: 'rect',
color: '1'
} satisfies Shape
typeof shape2 = {
type: 'rect';
color: string;
}
satisfies 키워드를 사용하면 다음과 같이 사용한 정확한 타입이 지정되는 것을 확인할 수 있다.
이를 통해 shape2.color.을 하게 되면 number와 관련된 모든 프로퍼티들이 노출되고, shape3.color.을 하는 경우 string과 관련된 모든 프로퍼티들이 노출된다.
readonly 설정을 위한 as const satisfies ${type} 구문 또한 사용이 가능하다.