let 동물 : string | number | undefined ;
라는 변수처럼 타입이 너무 많고 복잡할 때가 있다.
그럴 때 이제 type alias를 이용하면 된다.
type Animal = string | number | undefined;
let 돔울 : Animal;
이렇게 타입을 변수처럼 만들어서 쓴다.
관습처럼 type alias는 대문자로 시작하긴한다.
예를들어 아래와 같은 teacher라는 변수가 있다고 하자.
let teacher :{
name : string,
age : number,
} = {name : 'john', age: 20}
딱 봐도 복잡해 보인다.
하지만 type alias를 사용하면
type 사람 = {
name : string,
age : number,
}
let teacher: 사람 = {name:'john', age:30}
이렇게 깔끔하게 바뀐다.
const 여친 = {
name : '엠버'
}
여친.name = '유라';
원래 const 변수는 값이 변하지 않지만,
object 자료를 const에 집어넣으면 object 내부는 마음대로 변경이 가능하다.
type Girlfriend = {
readonly name : string,
}
let 여친:Girlfriend = {
name : '엠버'
}
여친.name = '유라';
자, 이렇게 readonly 키워드로 특정 속성을 변경 불가능하게 만들었다.
어떤 자료는 color, width 속성이 둘다 필요하지만
또 어떤 자료는 color 속성이 있어도 되고, 없어도 된다면
"?" 하나면 해결할 수 있다.
type Square = {
color ? : string,
width : number,
}
let 네모 : Square = {
width : 100
}
이러면 color 속성이 없어도 에러가 뜨지 않는 것을 확인 할 수 있다.
type User = {name:string, email:string, phone: string}
type Adult = {adult:boolean}
type NewUser = User & Adult;
let 정보:NewUser{
name : 'kim',
email : ggg@ggg.com
adult : false,
phone : 1234
}
대충 이렇게 해주면 될 것 같다.