타입스크립트의 인터페이스

posinity·2023년 6월 12일
0

Typescript

목록 보기
6/8

인터페이스는 상호 간에 정의한 약속 혹은 규칙을 의미한다.

interface personAge {
  age: number;
}

function logAge(obj: personAge) {
  console.log(obj.age);
}
let person = { name: 'Capt', age: 28 };
logAge(person);

인터페이스 정의하지 않은 속성들을 추가로 사용하고 싶을 때는 아래와 같은 방법을 사용한다.

interface CraftBeer {
  brand?: string;
  [propName: string]: any;
}

옵션 속성

옵션 속성은 다음과 같이 사용한다

interface CraftBeer {
  name: string;
  hop?: number;  
}

let myBeer = {
  name: 'Saporo'
};
function brewBeer(beer: CraftBeer) {
  console.log(beer.name); // Saporo
}
brewBeer(myBeer);

읽기 전용 속성

읽기 전용 속성은 인터페이스로 객체를 처음 생성할 때만 값을 할당하고 그 이후에는 변경할 수 없는 속성을 의미한다.
앞에 readonly를 붙힌다

interface CraftBeer {
  readonly brand: string;
}

let myBeer: CraftBeer = {
  brand: 'Belgian Monk'
};
myBeer.brand = 'Korean Carpenter'; // error!

읽기 전용 배열

배열을 선언할 때 ReadonlyArray<T> 타입을 사용하면 읽기 전용 배열을 생성할 수 있다.

let arr: ReadonlyArray<number> = [1,2,3];
arr.splice(0,1); // error
arr.push(4); // error
arr[0] = 100; // error

위처럼 배열을 ReadonlyArray로 선언하면 배열의 내용을 변경할 수 없다.

함수 타입 설정

interface login {
  (username: string, password: string): boolean;
}

let loginUser: login;
loginUser = function(id: string, pw: string) {
  console.log('로그인 했습니다');
  return true;
}

출처

타입스크립트 핸드북

profile
문제를 해결하고 가치를 제공합니다

0개의 댓글