Typescript 4.9에 추가
타입스크립트는 타입을 추론할 때 합리적인 기본 동작을 사용하는데, 이는 일반적인 경우에 코드를 쉽게 작성할 수 있도록 하기 위한 것입니다.
satisfies
를 추론된 타입에 영향을 주지 않고 입력을 확인합니다.다음 예를 생각해 봅시다:
type NamedCircle = {
radius: number;
name?: string;
};
const circle: NamedCircle = { radius: 1.0, name: 'yeah' };
// error because circle.name can be undefined
console.log(circle.name.length);
circle
의 선언타입 NamedCircle
에 따르면 변수를 초기화할 때 문자열 값을 제공했음에도 불구하고 name
필드가 실제로 정의되지 않았을 수 있기 때문에 타입 오류가 발생했습니다.
물론 : NamedCircle
타입 선언을 삭제할 수는 있지만, circle
객체에 대한 타입검사가 느슨해집니다. 이는 꽤나 딜레마입니다.
다행히 타입스크립트 4.9에는 추론된 타입을 변경하지 않고도 타입을 검사할 수 있는 새로운 satisfies
키워드가 도입되었습니다.
type NamedCircle = {
radius: number;
name?: string;
};
// error because radius violates NamedCircle
const wrongCircle = { radius: '1.0', name: 'ha' }
satisfies NamedCircle;
const circle = { radius: 1.0, name: 'yeah' }
satisfies NamedCircle;
// circle.name can't be undefined now
console.log(circle.name.length);
수정된 버전은 객체 리터럴이 NamedCircle
타입을 준수하도록 보장되고 추론된 타입에 non-nullable name
필드가 있다는 두 가지 이점을 모두 누릴 수 있습니다.
<aside> 💡 추론된 유형을 변경하지 않고 타입만 확인 할 수 있다.
</aside>