2021.11.18
타입스크립트 Interface / TypeAlias

Interface

클래스 또는 객체를 위한 타입을 지정할 때 사용되는 문법

  • interface 객체를 선언한 뒤 interface 객체를 사용할 때 내부에 존재하는 객체가 꼭 있어야 한다.
  • implements 키워드를 사용하여 해당 클래스가 Shape interface 의 조건을 충족하겠다는 것을 명시한다.
  • 객체의 타입을 지정할 때 ? 가 들어간 것은 설정을 해도 되고 안해도 되는 값이라는 것을 의미한다.
  • 타입이 동일하게 중첩되는 경우 중복되는 것을 지워주고 extends 를 이용하여 상속 받을 수 있다.
  • interface 에서 지정하지 않은 값을 작성했을 때에는 할당할 수 없음으로 오류가 뜬다.

 

사용법

interface 를 선언하고 interface 조건을 충족하는 클래스를 생성할 때

멤버 변수를 선언한 다음 consturctor 에 해당 값들을 하나하나 설정해주어야 한다.

  width: number;
  height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }
// Shape 라는 interface 선언
interface Shape {
    getArea(): number;
}

class Circle implements Shape {
    radius: number;   // *오류: 생성자에 할당되어 있지 않습니다. → 해결: constuctor 구현 

    constructor(radius: number) {
        this.radius = radius;
    }

    getArea() { // getArea 함수가 꼭 있어야 한다.
        return this.radius * this.radius * Math.PI; // 원의 너비를 구하는 함수 구현
    }
}
class Rectangle implements Shape {
    width: number;
    height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }

    getArea() {
        return this.width * this.height;
    }
}
const circle = new Circle(5);
const rectangle = new Rectangle(2, 5);

// shapes 는 inteface Shape 로 이루어진 배열로 circle 과 rectangle 을 넣어주었다.
const shapes: Shape[] = [circle, rectangle];

shapes.forEach(shape => {          // shapes 내부의 도형의 너비를 모두 더한 값을 출력
    console.log(shape.getArea());
})

 

public / private

constructor 의 파라미터 쪽에 public 또는 private 을 작성한다.

이를 통해 멤버변수를 선언하고 consturctor 에 해당 값을 하나하나 설정하는 작업을 생략해줄 수 있다.

public 으로 선언된 값은 클래스 외부에서 조회 가능하다.

private 으로 선언된 값은 내부에서만 조회 가능하다.

public, private 은 타입스크립트 내부에서만 유의미한 속성이다.

class Circle implements Shape {
    constructor(public radius: number) { // 클래스 외부에서 조회 가능
        this.radius = radius;
    }

    getArea() {
        return this.radius * this.radius * Math.PI;
    }
}

class Rectangle implements Shape {
    constructor(private width: number, private height: number) { // 클래스 내부에서만 조회 가능
        this.width = width;
        this.height = height;
    }

    getArea() {
        return this.width * this.height;
    }
}

따라서 circle 의 radius 값은 클래스 외부에서 조회할 수 있지만 rectangle 의 width 또는 height 값은 클래스 외부에서 조회할 수 없다.

 

일반 객체를 interface 로 타입 설정하기

interface Person {
    name: string;
    age?: number; // 물음표는 설정을 해도 되고 안해도 되는 값을 의미한다.
}
interface Developer {
    name: string;
    age?: number;
    skills: string[];
}

const person: Person = {
    name: '김사람',
    age: 20 // 없어도 오류나지 않음
}

const expert: Developer = {
    name: '김개발',
    skills: ['javascipt', 'react', 'typescript']
}

 

상속

interface Person {
    name: string;
    age?: number; // 물음표는 설정을 해도 되고 안해도 되는 값을 의미한다.
}
interface Developer extends Person { // extends 를 사용하여 Developer 가 Person 의 name 과 age 상속
    skills: string[];
}

const person: Person = {
    name: '김사람',
    age: 20 // 없어도 오류나지 않음
}

const expert: Developer = {
    name: '김개발',
    skills: ['javascipt', 'react', 'typescript']
}

 

 

Type Alias

type 은 특정 타입에 별칭을 붙이는 용도로 사용한다.

  • 객체를 위한 타입을 설정하거나, 배열 또는 어떤 타입이던 별칭을 지어줄 수 있다.
  • & 은 Intersection 으로서 2개 이상의 타입들을 합쳐준다.
type Person = {
    name: string;
    age?: number; // 물음표는 설정을 해도 되고 안해도 되는 값을 의미한다.
}
type Developer = Person & { // & 은 타입들을 합쳐준다.
    skills: string[];
}

const person: Person = {
    name: '김사람'
}

const expert: Developer = {
    name: '김개발',
    skills: ['javascipt', 'react', 'typescript']
}

type People = Person[]; // Person[] 를 People 이라는 타입으로 사용할 수 있다.
const people: People = [person, expert];

type Color = 'red' | 'orange' | 'yellow';
const color: Color = 'red';
const colors: Color[] = ['red', 'orange'];

 

 

용도

  • interface: 클래스와 관련된 타입. 라이브러리를 위한 타입을 설정하는 경우
  • typealias: 일반 객체의 타입의 경우엔 type 사용

어떤 것을 사용하던 일관성있게 쓰는 것이 좋다.