alias 란 별명이라는 뜻을 가지고 있는데, 타입 별명 이라는 뜻으로 해석 할 수 있다.
type alias를 사용하면 타입들에 별명을 부여해서, 가독성을 좋게하고 재사용성을 높일 수 있다.
type 별칭 = 타입;
type Animal = string | number | undefined;
const 동물: Animal = "강아지";
위처럼 Animal 이라는 별칭을 하나 만들고, 타입을 지정해놓으면 그 별칭에 맞는 타입값들을 사용할 수 있다.
type alias는 객체 타입에서 사용할때 유용하게 사용 할 수 있다.
type StudentType = {
id: number;
name: string;
checked: boolean;
};
const 학생1: StudentType = {
id: Math.floor(Math.random() * 10000),
name: "BRGNDY",
checked: true,
};
const 학생2: StudentType = {
id: Math.floor(Math.random() * 10000),
name: "PARKLEE",
checked: false,
};
위처럼 type을 따로 만들어주니 훨씬 가독성이 좋아진것을 확인할 수 있다.
일반적으로 const 로 변수를 지정하면 변수값은 변경이 안되지만, const 변수에 객체를 할당했을 경우에는 프로퍼티값이 변경이 가능하다.
type PersonType = {
name : string,
age : number,
isDeath : boolean
}
const 사람:PersonType = {
name : 'BRGNDY',
age : 999,
isDeath : false
}
사람.name = 'PARK';
console.log(사람.name); // PARK
type PersonType = {
readonly name : string,
age : number,
isDeath : boolean
}
const 사람:PersonType = {
name : 'BRGNDY',
age : 999,
isDeath : false
}
사람.name = 'PARK';
읽기 전용 속성이므로 할당할수 없다는 에러메세지가 나온다.
type PersonType = {
name: string;
age: number;
isDeath: boolean;
};
const 사람1: PersonType = {
name: "PARK",
age: 999,
isDeath: false,
};
const 사람2: PersonType = {
name: "LEE",
age: 999,
};
PersonType에 지정한 타입값들이 무조건 들어가야하기때문에 에러가 발생하는데, 만약에 프로퍼티에 ?를 붙여준다면 그 값은 있어도 , 없어도 된다.
type PersonType = {
name: string;
age: number;
isDeath ?: boolean;
};
const 사람1: PersonType = {
name: "PARK",
age: 999,
isDeath: false,
};
const 사람2: PersonType = {
name: "LEE",
age: 999,
};
⬆️ 에러가 나지 않는다.
type Name = string;
type Age = number;
type Person = Name | Age;
type PositionX = { x : number};
type PositionY = { y : number};
type NewType = PositionX & PositionY;
const position:NewType = {
x : 3,
y : 6
}
타입과 타입끼리 | 나 & 를 이용하여 하나의 타입으로 합쳐줄 수 있다.
type PositionX = { x : number};
type PositionX = {x : string};
type Person = {
name :string,
age : number,
isDeath : boolean
}
type Person2 = {
name : string,
age2 : number,
}
type NewType = Person & Person2
const person :NewType = {
name : 'BRGNDY',
age : 999,
isDeath : true,
age2 : 123,
}
한개의 속성만 입력해주면 되지만, 다른 속성값들은 다 입력해주어야한다.