[TypeScript] Interface(인터페이스)

종현·2023년 12월 19일

[TypeScript]

목록 보기
3/19

interface란?

  • 객체의 타입을 정의할 때 사용하는 문법

interface로 타입을 정의할 수 있는 부분들

  • 객체의 속성과 타입

  • 함수의 파라미터와 반환 타입

  • 함수의 파라미터 개수와 반환값 여부

  • 배열과 객체의 접근하는 방식

  • 클래스

interface를 이용한 객체의 타입 정의

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

const me: Human = {name: 'jonghyun', age: 99};
const me: Human = {name: 'jonghyun', age: '99'}; // 에러 - 타입이 number인 age가 string
const me: Human = {name: 'jonghyun', age: 99, hobby: 'futsal'}; // 에러 - Human interface에 hobby가 없음

interface를 이용한 함수 타입 정의

  • 함수의 파라미터 타입 정의
interface Human {
  name: string;
  age: number;
}

function logName(person: Human) {
  console.log(person.name);
}

const me = {name: 'jonghyun', age: 99};

logName(me); // jonghyun
  • 함수의 반환 타입 정의
interface Human {
  name: string;
  age: number;
}

function logName(person: Human): Human {
  return person
}

interface의 옵션 속성

interface Human {
  name: string;
  age?: number; // ?를 사용하여 있어도되고 없어도되는 옵션 속성으로 만들 수 있다.
}

function logName(person: Human) {
  console.log(person.name);
}

const me = {name: 'jonghyun'};

logName(me); // jonghyun

interface 상속

  • class의 상속과 같은 extends예약어를 사용하여 interface Me를 Developer가 상속받아 사용할 수 있다.
interface Me {
  name: string;
  age: 99;
}

interface Developer extends Me {
  position: string;
}

const jonghyun: Developer = {name: 'jonghyun', age: 99, position: 'frontEnd'};

interface를 이용한 인덱싱 타입 정의

  • 배열의 인덱싱 타입 정의
interface StringArray {
  [index: number]: string;
}

const hobby: StringArray = ['futsal', 'soccer', 'lol'];

hobby[0]; // futsal
  • 객체의 인덱싱 타입 정의
interface Career {
  [level: string]: string;
}

const career: Salary = {
  junior: '100원',
  middle: '300원',
  senior: '500원',
}

career['junior'] // 100원
career['middle'] // 300원
career['senior'] // 500원

인덱스 시그니처란?

  • 정확한 속성 이름을 명시하지 않고 속성 이름의 타입과 속성 값의 타입을 정의하는 문법을 의미한다.

  • 객체의 속성 이름과 개수가 구체적으로 정의되어 있다면 일일이 타입을 명시하는것이 더 효과적이다.

  • 코드를 작성할 때 구체적으로 어떤 속성이 제공될 지 알 수 없어 자동완성이 되지 않는다.

  • 속성 이름은 모르지만 속성 이름의 타입과 값의 타입을 아는 경우에 활용한다.

interface Career {  
  // 인덱스 시그니처를 사용하여 속성 이름이 string이고 값이 string이라면 어떤 속성이든 추가할 수 있다.
  [level: string]: string; 
}

출처: 쉽게 시작하는 타입스크립트

profile
지속 가능한 성장 습관을 만들어 나가고 싶어요!

0개의 댓글