[Typescript] 타입 별칭

Narcoker·2025년 3월 17일

Typescript

목록 보기
1/15

타입 별칭

타입을 변수처럼 사용하는 문법

아래처럼 같은 속성을 가진 객체가 여럿일 경우 매번 같은 타입을 작성해줘야한다.

이로 인해 코드의 중복이 발생함으로써 가독성이 떨어지고 유지보수가 어려워진다.

let user1: {
	id: number;
	name: string;
	birth: string;
	location: string;
} = {
	id: 1,
	name: "Alice",
	birth: "1998.06.08"
	location: "서울"
}

let user2: {
	id: number;
	name: string;
	birth: string;
} = {
	id: 2,
	name: "Bob",
	birth: "1998.12.12"
	location: "부천"
}

이를 해결하기 위해서 타입 별칭을 사용한다.

타입을 선언하고 변수에 지정해준다.

type User = {
	id: number;
	name: string;
	birth: string;
	location: string;
}

let user1: User = {
	id: 1,
	name: "Alice",
	birth: "1998.06.08"
	location: "서울"
}

let user2: User = {
	id: 2,
	name: "Bob",
	birth: "1998.12.12"
	location: "부천"
}

type은 블록스코프이며 const와 같이 중복으로 선언할 수 없다.

자바스크립트로 변환되면 타입 별칭 정의는 모두 사라진다.

출처

인프런 - 한 입 크기로 잘라먹는 타입스크립트

profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글