type Person = {
name : string;
age : number;
};
let person = {} as Person; // 해당 타입으로 간주하라고 알려줌 (타입 단언)
// 이는 타입 단언을 해주지 않으면 person 객체가 바라보는 타입이 없어 안됨
person.name = "박정수";
person.age = 26;
type Dog = {
name : string;
color: string;
};
let dog = {
name: "돌돌이",
color: "brown",
breed:"진도",
} as Dog; // 초과되는 breed는 Dog타입으로 단언하면 해당 dog 객체는 Dog타입으로 추론까지 됨
*** 값 as 단언 <- 단언식
* A as B
* A가 B의 슈퍼타입이거나
* A가 B의 서브타입이어야 함**
let num1 = 10 as never;
let num2 = 10 as unknown;
// let num3 = 10 as string; // 두 타입은 겹치는 게 없어서 교집합이 없는 타입
let num3 = 10 as unknown as string; // 근데 이렇게 하면 됨 (다중 단언) -> 좋은 방법 아님 어쩔 수 없을 때만 사용
→ 객체 타입에 이용할 때 효과 있음 (readonly 만듬)
let num4 = 10 as const; // 이러면 넘버 리터럴 타입으로 추론 됨
// 여기서 객체에 const 단언하면 객체 프로퍼티가 모두 readonly로 추론 된다.
let cat = {
name : "야옹이",
color: "yellow",
} as const;
type Post = {
title: string;
author?: string;
};
let post :Post = {
title: "게시글1",
author: "박정수"
}
// 여기서 ?은 js에서 제공하는 옵셔널 체이닝이라는 것
// author 프로퍼티의 값이 null이거나 undefined일 경우에 .표기법 접근하면 오류 발생하니
// ?를 붙여주면 해당 author값이 없으면 값 전체를 undefined 되도록 만들어줌
// 아래애서는 그래서 number 타입이 안될 수도 있기에 에러남
// const len : number = post.author?.length;
// 하지만 ? 를 !로 바꾸면 이 값이 null이거나 undefined가 아닐거라고 믿도록 만듬(좀 위험함 확실할때만 써라)
const len : number = post.author!.length;