[TS] type alias & readonly 타입

phoenix·2021년 10월 11일
0

type 키워드를 사용하여 타입을 변수에 담기

type Food = string | number | undefined

let food :Food = 123;

//오브젝트형도 똑같은 원리이다

type Food = {name : string, price : number}

let food :Food = {name : '김치찌개', price : 7000}

type alias를 작명할때는 항상 영어 대문자로 시작하는 관습이 있다. 일반 변수와 차별화를 두기 위해

readonly를 통하여 객체에있는 속성값 변환 막아주기

type Food = {
  readonly name : string
}

const lunch :Food = {
  name : '김치찌개'
}

lunch.name = '파스타'(이렇게 변경을 하려고 하면 오류가 뜬다)

//이렇게 readonly를 사용하면 값이 변환되는거를 막아준다 하지만
//타입스크립트의 에러는 에디터 와 터미널에서만 존재해서
//자바스크립트 파일로 가면 잘 변환 되어 있다
type Name = string;
type Price = number
type Food = Name | age;
//이렇게 type alias 또한 union type으로 합치기가 가능하다
//또는

type PositionX = { x : number};
type PositionY = { y : number};
type Position = PositionX & PositionY;
//이렇게 하면 Position = { x:number, y:number } 오브젝트 타입이 합체가 된다
profile
phoenix

0개의 댓글