type 타입변수명 = 타입종류
타입 정의가 너무 길면 타입을 변수처럼 만들어서 쓰는 alias 문법
관습적으로대문자로 시작
일반 자바스크립트 변수랑 차별을 두기 위해 AnimalType 이런 식으로도 작명
type Animal = string | number | undefined;
let 동물 :Animal;
type 사람 = {
name : string,
age : number,
}
let teacher :사람 = { name : 'john', age : 20 }
const 출생지역 = 'seoul';
출생지역 = 'busan'; //const 변수는 여기서 에러남
const 변수는 값이 변하지 않는 변수를 만들고 싶을 때 사용
const 여친 = {
name : '엠버'
}
여친.name = '유라'; //const 변수지만 에러안남
하지만 object 자료를 const에 집어넣어도 object 내부는 마음대로 변경가능
const 변수는 재할당만 막아줄 뿐이지 그 안에 있는 object 속성 바꾸는 것 까지 관여하지 않기 때문
object 속성을 바뀌지 않게 막고 싶으면 readonly 키워드 사용
특정 속성을 변경불가능하게 잠궈줌
type Girlfriend = {
readonly name : string,
}
let 여친 :Girlfriend = {
name : '엠버'
}
여친.name = '유라' //readonly라서 에러남
object자료는 color, width 속성이 둘다 필요하지만
어떤 object 자료는 color 속성이 선택사항이라면
물음표연산자만 추가하면 됨
type Square = {
color? : string,
width : number,
}
let 네모2 :Square = {
width : 100
}
OR 연산자를 이용해서 Union type을 만들 수도 있음
type Name = string;
type Age = number;
type NewOne = Name | Age;
object에 지정한 타입의 경우 합치기(extend)도 가능
type PositionX = {x: number}
type PositionY = {y: number}
type NewType = PositionX & PositionY //{x: number, y: number}
let position:NewType = {x:10, y:20}
& 기호를 쓴다면 object 안의 두개의 속성을 합쳐줌
위 코드에서 XandY 타입은 { x : number, y : number } 이렇게 정의됨
Type alias & Type alias 만 가능한게 아니라
Type alias & { name : string } 이런 것도 가능
**type 키워드는 재정의가 불가능
type Name = string;
type Name = number;
< 연습 1 >
object 타입을 정의한 type alias 두개를 & 기호로 합칠 때 중복된 속성이 있으면 어떻게 될까요?
type MyType = {
color? : string,
size : number,
readonly position : number[]
}
let 테스트용변수 :MyType = {
size : 123,
position : [1,2,3]
}
< 연습 2 >
type User = { name : string, email? : string, phone : string }
type Adult = { adult : boolean }
type NewUser = User & Adult;
let 회원가입정보 :NewUser = {
name : 'kim',
adult : false,
phone : 1234
}