본문으로 바로가기

interface 기본

 

(https://typescript-kr.github.io/pages/interfaces.html)

(typescript-handbook-ko.org/pages/interfaces.html)

 

interface는 object의 type을 체크해주는 ts의 고유한 문법이다. object 각 요소들의 타입을 따질 때 편리하다. interface는 TS 문법이기 때문에 컴파일 될 때 js로 컴파일이 되지 않는다. 컴파일된 js파일을 살펴보면 확인할 수 있다.

 

활용하는 방법은 아래와 같다.

interface Human {
  name: string;
  age: number;
  boo(): void;
}

const person: Human = {
  name: "da",
  age: 5,
  boo: () => console.log("this is boo"),
};

const booboo = (a: Human): void => {
  console.log(`${a.name} is ${a.age} years old`);
};

booboo(person); // da is 5 years old
person.boo(); // this is boo

 

함수의 모습까지 인터페이스로 지정 가능

// 함수의 전체 타입에 사용하는 경우
interface SumFunction {
  (a: number, b: number): number;
}


let summ: SumFunction;
summ = function (num1: number, num2: number): number {
  return num1 + num2;
};

 

Read-only properties

interface 속성 앞에 readonly를 붙여주면 초기화 이후 값을 변경할 수 없게 됩니다.

interface Human {
  readonly name: string;
  age?: number;
}

const person: Human = {
  name: "da",
};

// 객체 내 속성 변경 불가능
person.name = "foo";

export {};

 

인덱서블 타입 (Index Signatures(Indexable types))

 

지금까지 사용한 인터페이스는 직접 속성의 타입을 지정해주었습니다. 그러나 객체, 배열과 같은 경우 속성이 많이 들어갈 경우 하나하나 타이핑을 해줄 수는 없는 경우도 있습니다. 또는 어떤 속성이 들어갈 지 확정지을 수 없는 경우도 있고요. 이 경우에는 인덱서블 타입을 활용하는 것이 좋습니다.

 

[인덱서]의 타입은 string과 number만 지정할 수 있습니다. 이는 생각해보면 당연한게 객체의 key는 문자만 되고(object.key), 배열은 인덱스(array[0])는 숫자이까요.

 

조금 생소한 개념이니 예시를 많이 들어보겠습니다.

interface DictIndex {
  [whatever: string]: string; // key가 string, value가 string
}

const dict: DictIndex = {
  name: "darren",
  job: "entreprenuer",
  age: 100, // error!
};
interface DictIndex {
  [whatever: string]: { id: number; name: string }; // key가 string, value가 {id, name}꼴
}

const dict: DictIndex = {
  first: { id: 1, name: "darren" },
  second: { id: 2, name: "mary" },
};
interface StringRegexDict {
  [key: string]: RegExp;
}
const object: StringRegexDict = {
  sth: /abc/,
};
// 배열의 인덱싱에 사용하는 경우
interface StringArray {
  [index: number]: string; // key가 숫자, value가 string
}
let array: StringArray = [];

array[0] = "hi";
array[1] = 3; // error
interface PhoneNumberDictionary {
  [phone: string]: {
    num: number;
  };
}

interface Contact {
  name: string;
  address: string;
  phones: PhoneNumberDictionary;
}

// 아래와 같은 꼴을 타이핑할 수 있게 됨
{
  name: "Tony",
  address: "Malibu",
  phones: {
    home: {
      num: 11122223333,
    },
    office: {
      num: 44455556666,
    },
  },
},

 

extends

class처럼 extends할 수도 있습니다.

// 인터페이스 확장
interface IPerson {
  name: string;
  age?: number;
}
interface IDeveloper extends IPerson {
  language: string;
}
const joo: IDeveloper = { name: "joo", age: 20, language: "ts" };

 

 

 

 

 

darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체