타입 추론을 그대로 활용하면서 추가로 타입검사를 하고 싶을 때 사용
Copy // sirius 대신 sriius로 오타낸 상황
const universe = {
sun: "star",
sriius: "star", // sirius 오타
earth: { type: "planet", parent: "sun" },
}
// key: sun | sriius | earth
// value: {type: string, parent: string } | string
Copy const universe: {
[key in 'sun' | 'sirius' | 'earth']: { type: string, parent: string } | string
} = {
sun: "star",
sriius: "star", // sirius 오타 잡힘
earth: { type: "planet", parent: "sun" },
}
}
Copy universe.earth.type;
// Property 'type' does not exist on type 'string | {type: string; parent: string;}',
// Property 'type' does not exist on type 'string'
객체 리터럴 뒤에 'satisfies' 를 표기하면 된다.
Copy const universe = {
sun: "star",
sriius: "star", // sirius 오타
earth: { type: "planet", parent: "sun" },
}
// 추론된 타입 (정확하게 추론된다.)
const universe: {
sun: string;
sriius: string;
earth: {
type: string;
parent: string;
}
}
// satisfies 사용
const universe = {
sun: "star",
sriius: "star", // sirius 오타
earth: {type: "planet", parent: "sun"},
} satisfies {
[key in 'sun' | 'sirius' | 'earth']: { type: string, parent: string } | string
}
Copy type NamedCircle = {
redius: number;
name?: string;
}
const circle: NamedCircle = {radius: 1.0, name: 'woong'};
// circle.name은 optional type으로 undefined일 수 있기 때문에 오류 발생
console.log(circle.name.length);
Copy type NamedCircle = {
redius: number;
name?: string;
}
// radius가 NamedCircle을 위반하여 오류 발생
const wrongCircle = {radius: '1.0', name: 'woong'};
satisfies NamedCircle;
/* 객체 리터럴이 NamedCircle 타입과 일치하도록 보장되며
* 추론된 타입은 name 필드가 옵셔널이 아닌 필드가 된다.
*/
const circle = {radius: 1.0, name: 'woong'};
satisfies NamedCircle;
// circle.name은 undefined가 될 수 없다.
console.log(circle.name.length);