타입스크립트 type alias & readonly

버건디·2023년 1월 3일
0

타입스크립트

목록 보기
6/12
post-thumbnail

🔍 Type Alias 란 ?

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을 따로 만들어주니 훨씬 가독성이 좋아진것을 확인할 수 있다.

alias 를 만들때는 일반 변수들과 구분짓기 위해 대문자 + Type 이라는 네이밍 규칙을 따라주는것이 좋다.

🔍 readonly 란?

일반적으로 const 로 변수를 지정하면 변수값은 변경이 안되지만, const 변수에 객체를 할당했을 경우에는 프로퍼티값이 변경이 가능하다.

type PersonType = {
  name : string,
  age : number,
  isDeath : boolean
}

const 사람:PersonType = {
  name : 'BRGNDY',
  age : 999,
  isDeath : false
}

사람.name = 'PARK';

console.log(사람.name); // PARK

이럴때, 객체의 불변성을 유지하고 싶다면 readonly 속성을 사용하면 된다.

type PersonType = {
 readonly name : string,
  age : number,
  isDeath : boolean
}

const 사람:PersonType = {
  name : 'BRGNDY',
  age : 999,
  isDeath : false
}

사람.name = 'PARK';

읽기 전용 속성이므로 할당할수 없다는 에러메세지가 나온다.

어떤 변수엔 isDeath가 들어가지만, 어떤 변수엔 isDeath 프로퍼티가 없다면?

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 Alias는 여러개로 합칠수도 있다.

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을 지정한 경우앤 재정의가 불가능하다.

type PositionX = { x : number};
type PositionX = {x : string};


- 객체 타입을 정의한 type alias 두개를 & 기호로 합칠 때 중복된 속성이 있으면 어떻게 될까?

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,
}

한개의 속성만 입력해주면 되지만, 다른 속성값들은 다 입력해주어야한다.

profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글