📎아이템 9 타입 단언보다는 타입 선언을 사용하기
interface Person { name: string };
const alice: Person = { name: 'Alice' }; // 타입은 Person
const bob = { name: 'Bob' } as Person; // 타입은 Person📍 타입 선언과 타입 단언
const alice: Person = {};
// ~~~~~ Property 'name' is missing in type '{}' but required in type 'Person'
const bob = {} as Person; // No errorconst alice: Person = {
name: 'Alice',
occupation: 'TypeScript developer'
// ~~~~~~~~~ Object literal may only specify known properties,
// and 'occupation' does not exist in type 'Person'
};
const bob = {
name: 'Bob',
occupation: 'JavaScript developer'
} as Person; // No error화살표 함수
타입 단언이 꼭 필요한 경우
DOM 엘리먼트에 접근하는 경우
자주 쓰이는 특별한 문법(!)을 사용해서 null이 아님을 단언하는 경우
타입 단언문으로 타입 간 변환
📍 요약
Last updated