리코딩 : 타입스크립트(TypeScript)

타입스크립트 (TypeScript) - 인터페이스

BreezeBm 2021. 10. 15. 19:58

출처 : 구글이미지

01. 타입스크립트 인터페이스

 타입스크립트를 쓰면서 인터페이스를 처음봤을 때, 음... 뭘까? 생각이 많이 들었다. 쓰다보면 드는 생각은 인터페이스는 여러개의 타입을 가지고 있는 것을 정의하는 것 같다. 문자열이면 string, 숫자면 number 이렇게 주듯이 내가 필요한 타입을 만드는 것이다. 인터페이스는 프로퍼티와 메소드를 가질 수 있다. 이점은 Class와 유사한데, 직접 인스턴스를 생성할 수는 없고 추상 메서드 이다.

 

02. 인터페이스 사용

// 인터페이스 사용
interface SquidGame {
  order: number;
  name: string;
  isFinished: boolean;
};

let first: SquidGame;

first = { order: 1, name: "Red Light, Green Light", false }

인터페이스에는 이전에 기록했던 타입들을 하나씩 지정해줄 수 있다. 그리고 이 인터페이스로 선언한 변수는 반드시 인터페이스 안에 있는 타입을 지켜야한다. 아까 말했듯이, 새롭게 내가 타입을 만들어서 정의하는 것이다.


// 옵션 속성
interface Participant {
  No?: number;
  name: string;
};

let men = {
  name: "Il Nam Oh";
};

function sayJoin(person: Participant): void {
  console.log(`${person.name} joined the Game!`);
};

sayJoin(men);

선택적 변수처럼 인터페이스도 ?를 넣을 수 있다. 이를 옵션 속성이라고 한다. 참가자의 번호를 뜻하는 No에 ?를 붙여서 이 속성은 있어도 되고, 없어도 되도록 설정했다. 함수를 실행하면 men에는 No가 없지만 문제없이 작동한다.


// readonly
interface Participant {
  readonly No: number;
  name: string;
};

let men: Participant = {
  No: 456,
  name: "Ki Hoon Sung";
};

men.No = 1; // 에러발생

readonly속성을 설정하게 되면, men이라는 객체에서 No 값을 객체를 처음 생성할 때만 값을 할당하게 되고, 이후에는 재할당을 불가하게 만든다. 


interface Participant {
  name?: string;
};

function sayJoin(person: Participant): void {
  console.log(`${person.name} joined the Game!`);
};

sayJoin({nane: "Ji Young"}); // 에러발생

에러가 발생한 이유를 찾아보면, interface에는 name이라고 설정해 주었는데, 함수의 인자로 nane을 주었기 때문에 에러가 발생한다. 타입스크립트는 타입을 추론하기 때문에 꼼꼼히 봐준다! 타입 추론을 무시하고 싶은 경우에는 다음과 같이 쓴다.

let gganbu = { nane: "Ji Young" };
sayJoin(gganbu as Participant);

// 인터페이스로 정의되지 않은 속성을 사용하고 싶을 때는 아래와 같이 사용한다.
interface Paticipant {
  name?: string;
  [propName: string]: any;
};

// 인터페이스와 함수 : 변수와 반환겂을 정의
interface CountPeople {
  (num: number): void;
}

const countPeople: CountPeople = function (num: number) {
  console.log(`${456 - num} left`)
}

console.log(countPeople(200)); // 256

// 인터페이스 사용 : implements
interface SquidGame {
  order: number;
  name: string;
  isFinished: boolean;
};

class Game implements SquidGame {
  constructor(
    public id: number,
    public content: string,
    public completed: boolean,
  ) { }
}

const dalgona = new Game(2, 'Dalgona', 'true');

// 인터페이스 상속
interface Prize {
  prize: string;
}

interface Winner extends Prize {
  winner: string;
};

const winner: Winner = {
  prize: '45,600,000,000won',
  name: "spolier";
};

인터페이스는 함수도 지정할 수 있다. 변수와 반환되는 값을 정의할 수 있다. 그리고 class 선언문에 implement를 선언해서 사용할 수 있다. 그리고 반드시 클래스는 해당 interface를 따라야 한다. 그리고 인터페이스 상속도 가능하다. extends 키워드를 사용해서 인터페이스를 상속받을 수 있고, 여러개를 받을 수 있다. 

 

공부공부...