TypeScript: Interface Ep.1

What are Interfaces


Interface

타입을 만들어 내는 방식이다.
자바스크립트에는 전혀 없는 문법이다.
interface는 컴파일 타임에만 필요하다. 컴파일 타임에 interface를 이용해서 문제가 없는지 관계를 규명해서 체크해주는 역할을 한다. 이로 인해, 에러 발생 여부를 알게 되어 문제가 있는지를 확인 할 수 있다.

  • interface 미사용

    function hello(person: { name: string; age: number } ): void {
      console.log(`안녕하세요! ${person.name}입니다.`)
    }
      
    const p1: { name: string; age: number } = {
      name: 'Mark',
      age: 39,
    };
      
    hello(p1);
    
  • interface 사용

    interface Person1 {
      name: string; 
      age: number;
    }
      
    function hello(person:  Person1 ): void {
      console.log(`안녕하세요! ${person.name}입니다.`)
    }
      
    const p1:  Person1 = {
      name: 'Mark',
      age: 39,
    };
      
    hello(p1);
    
  • ts파일을 js파일로 변환한 결과

    interface를 사용한 부분은 사라졌다. 자바스크립트에서는 없는 문법이기 때문이다.

    "use strict";
    function hello(person) {
        console.log(`안녕하세요! ${person.name}입니다.`);
    }
    const p1 = {
        name: 'Mark',
        age: 39,
    };
    hello(p1);
    

Optional property (1)


name은 항상 있어야 하는 타입이지만, age는 있을 수도 있고 없을 수도 있다면 ‘물음표’를 달아주면 된다.
hello2를 출력할때 age를 설정하지 않아도 오류가 발생하지 않는다.

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

function hello2(person:  Person2 ): void {
  console.log(`안녕하세요! ${person.name}입니다.`)
}

hello2({ name: 'Mark', age: 39 });
hello2({ name: 'Anna' });

Optional property (2)


Indexable type

말 그대로 index를 사용하여 만드는 타입이다.
[]안에 index의 원하는 타입을 지정하고 : 뒤에는 해당 인덱스 안에 들어올 타입을 지정해준다.

interface Person3 {
  name: string;
  age?: number;
  [index: string]: any;
}

function hello3(person:  Person3 ): void {
  console.log(`안녕하세요! ${person.name}입니다.`)
}

const p31: Person3 = {
  name: 'Mark',
  age: 39,
};
  • string ⇒ sister / any ⇒ ‘Sung’, ‘Chan’

    const p32: Person3 = {
      name: 'Anna',
      sister: ['Sung', 'Chan'],
    }
    
  • string ⇒ father, mother / any ⇒ p31, p32

    any이기 때문에 객체가 들어가도 상관이 없다.

    const p33: Person3 = {
      name: 'Bromang',
      father: p31,
      mother: p32,
    }
    
  • 물음표와 indexable의 차이점

    물음표: property의 이름이 명시되어 있고 해당 property가 있는 지 없는 지를 명시한다.

    indexable: 어떤 이름의 property가 와도 괜찮다. 어떤 property이던지 추가로 설정할 수 있다.

Comments