rhanziy

TS - type alias와 readonly 본문

Html_css_js

TS - type alias와 readonly

rhanziy 2023. 1. 5. 18:00

type 키워드를 써서 가독성과 확장성을 높일 수 있다. 간단쓰

type Animal = string | number | undefined;
let animal :Animal = 'cat';


// obj일 때
type Animal = { name :string, age :number }
let 동물 :Animal = { name : 'munzi', age : 10 }

 

 

const 변수는 등호할당만 막아지는데, 오브젝트 자료형일 경우 아래와 같이 실수로 수정을 할 수 있음.

const 출생지역 = { region : 'seoul' }
출생지역.region = 'busan'

 

 

타입스크립트에서는 readonly 기능을 통해 타입스크립트 자체에서 error를 띄워줄 수 있다.

type Cat = { 
    readonly name? :string 
    // = name : string | undefiend 
}

const cat:Cat = {
    name : '먼지'
}
cat.name = '둥지';  // error

 

 

type 끼리 extend도 가능.

type Name = string;
type Age = number;
type Person = Name | Age;

// &연산자로 obj 타입 extend
type PositionX = { x : number };
type PositionY = { y : number };
type NewType = PositionX & PositionY;

let position :NewType = { x : 10 , y : 20 };

 

좀 더 이해가 쉽게 연결시켜보면~

type User ={
    name : string,
    phone : number,
    email : string
}
type Adult = {
    adult : boolean
}

type NewUser = User & Adult;

let 회원가입정보 :NewUser = {
    name : 'kim',
    phone : 123,
    email : '123@123',
    adult : true
}

 

Comments