본문 바로가기
프로그래밍 개발/Typescript

Typescript 인터페이스(Interface)

by Jinseok Kim 2021. 5. 6.
반응형

인터페이스(Interface)

 

 

기본 interface

interface Person {
    name: string;
    age: number;
}

const p1: Person = { name: 'jin', age: 23};
const p2: Person = { name: 'seok', age: 'ten'} //age 오류

interface라는 기능을 이용하면 따로 타입 지정하는 코드를 분리할 수 있게 된다.

 

 

interface Person {
    name: string;
    age?: number;
}

const p1: Person = { name: 'jin'};
  • interface 안에서도 선택 속성을 사용할 수 있다.
  • age에 선택 속성을 적용시켰기 때문에 Person interface을 지정한 p1의 객체에 age가 정의되어 있지 않아도 오류가 등장하지 않는다.

 

 

interface Person {
    name: string;
    age: number | undefined;
}

const p1: Person = { name: 'jin', age: undefined};

하지만 선택 속성인 '?'을 쓰지 않고 위에 처럼 union을 사용한다면 age을 객체안에 있어야한다. 정의하기 싫다해도undefined라고 일단은 적어주어야 오류가 등장하지 않는다.

 

 

 

 

 

readonly

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

const p1: Person = { name: 'jin'};

p1.name = 'jone' //name 오류

const p2: Person = { name: 'jin', birthday: '1997-01-01'}; //birthday 오류
  • readonly라는 기능을 특정 타입에 지정해주면 해당 적용된 객체 값이 변화가 되면 오류가 등장하게끔 할 수 있다.
  • 또 interface에 타입이 정의되지 않은 객체가 있다면 곧바로 오류가 등장하게 하는 기능 또한 존재하여 타입 작성의 실수를 줄일 수 있다.

 

 

 

index type

interface Person {
   readonly name: string;
    age: number;
    [key: string]: string | number;
}

const p2: Person = { name: 'jin', age: 25, birthday: '1997-01-01'};
  • 위의 코드는 index type을 이용한 예이다. 인덱스 타입은 객체의 키 이름이 string이면 모두 타입 통과를 할 수 있게끔하는 기능이다.
  • 보면 birthday 라는 키 이름이 Person 인터페이스에 존재하지 않지만 [key: string]라는 인덱스 타입으로 인하여 string이라는 키 이름이기만 하면 타입 통과할 수 있도록 해주는 것이다.
  • 직접적으로 age나 name으로 타입을 지정한 키 이름들은 인덱스 타입에 영향을 받지 않는다.

 

 

인터페이스의 객체 키 이름

interface Person {
  [year: number]: A;
  [year: string]: B;
}

interface Person {
  [year: number]: number; //오류
  [year: string]: string;
}

interface YearPriceMap {
  [year: number]: number; //통과
  [year: string]: string | number ; //통과
}
  • 예를 들자면 자바스크립트에서는 객체의 키 이름이 숫자인 경우 내부적으로 값을 문자열string으로 바꾸어 인식하기 때문에 A는 B로 할당이 가능해야 한다.
  • 키 이름이 string인 값에 키 이름이 number인 값의 number가 할당이 가능하지 않으면 오류가 등장한다

 

 

interface YearPriceMap {
  [year: number]: number;
  [year: string]: string | number ;
}

  const yearMap: YearPriceMap = {};
  yearMap[1998] = 1000;
  yearMap[1998] = 'abc'; //[1998] 오류
  yearMap['2000'] = 1234;
  yearMap['2000'] = 'jinseok';
  • 위의 코드를 보면 키 이름이 숫자일때는 값이 숫자이면 통과가 되지만 문자열 값이 들어가면 오류를 등장시킨다.
  • 대신 키 이름이 문자열일때는 값이 문자열이든 숫자이든 상관없이 통과 된다.

 

 

 

 

interface 함수 타입 정의

interface GetText {
    (name: string, age: number): string;
}

const getText: GetText = function (name, age) {
    const nameText = name.substr(0, 10);
    const ageText = age >= 35 ? 'jin' : 'seok';
    return `name: ${nameText}, age: ${ageText}`;
};

 

위와 같이 인터페이스를 이용하여 함수 타입을 정의할 수도 있다.

 

 

interface GetText {
    (name: string, age: number): string;
    totalCall?: number; //함수 속성값 타입 정의
}

const getText: GetText = function (name, age) {
 if(getText.totalCall !== undefined){
     getText.totalCall += 1;
     console.log(`totalCall: ${getText.totalCall}`)
 }
 return '';
};

getText.totalCall = 0; //함수 속성값 삽입
getText('', 0);
getText('', 0);

// 1
// 2

이렇게 인터페이스로 함수 타입을 정의할때 함수의 속성 값을 정의할 수있고 그래서 함수를 만들어 놓고 속성 값을 넣어줄 수도 있다.

 

 

 

 

인터페이스 확장

interface Perosn {
    name: string;
    age: number;
}
interface Korean extends Perosn {
    isLiveSeoul: boolean;
}

// interface Korean {
//     name: string;
//     age: number;
//     isLiveSeoul: boolean;
// }

extends을 이용하여 Korean이라는 인터페이스에 Person 인터페이스의 정보를 붙여주어 Korean 인터페이스의 정보를 확장시키줄 수도 있다.

 

 

 

인터페이스 교차

interface Perosn {
    name: string;
    age: number;
}
interface Product {
    name: string;
    price: number;
}

type PP = Perosn & Product;
const pp: PP = {
    name: 'a',
    age: 23,
    price: 1000
};
  • 위에 처럼 & 라는 교차 기능을 이용하여 교집합 형식의 인터페이스 정보를 합칠 수 있다.
  • name은 공통 된 것이라 하나로 통일되고 age와 price가 각각의 인터페이스에서 합쳐져 새로운 type 정의를 만들어 냈다.
반응형

'프로그래밍 개발 > Typescript' 카테고리의 다른 글

Typescript 재네릭  (0) 2021.05.07
Typescript 타입 호환성  (0) 2021.05.07
Typescript 함수 타입  (0) 2021.05.05
Typescript enum 타입  (0) 2021.05.05
Typescript 기본 타입 정의하기  (0) 2021.05.05

댓글