개발공부/타입스크립트

Interface, Type Alias

jennayeo 2021. 6. 29. 15:48

Interface는 클래스 또는 객체를 위한 타입을 지정할때 사용된다.

 

클래스 선언할때 특정 인터페이스 implement하기

Shape이란 interface를 만들어 넓이 구하기

// shape이란 interface에는 getArea라는 함수가 있어야하고, 그 함수의 결과물은 number이다.
interface Shape {
    getArea(): number;
}

// circle이란 클래스가 Shape인터페이스를 구현하도록 처리
class Circle implements Shape {
    radius: number;

    constructor(radius: number) { // constructor가 없으면 rardius에 빨간줄 뜸
        this.radius = radius;
    }

    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는 Shape interface로 이루어진 배열인데, 이 배열에 circle, rectangle을 넣어준다.
const shapes: Shape[] = [circle, rectangle];

shapes.forEach(shape => {
    console.log(shape.getArea());
});

결과 출력하기

yarn run ts-node ./src/practice.ts

 

현재는 radius를 받아와서 this.radius로 넣어주고있는데, 이것을 public과 private을 사용하여 자동화 시켜주자

그리고 new Circle(5)을 담아둔 circle변수아래에서 circle.radius와 같이 circle에 뭐가들었는지 조회가능하다.

반면, private은 circle안에 뭐가 들어있는지 조회 불가능하다.

*public과 private은 컴파일 후엔 의미없음

 

인터페이스를 사용하여 객체 타입 지정하기

interface Person {
    name: string;
    age?: number; // ?를 사용하면 age의 값이 있을수도있고 없을수도있음
}

const person: Person = {
    name: 'hello world',
    age: 21 // age값을 안넣어도 아무 에러안뜸, 하지만 interface에서 지정하지 않은 값이 들어간다면 에러 뜸
}

interface 상속받기

// 수정 전
// Person과 Actor의 name, age값이 중첩되고있다.

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

interface Actor {
    name: string;
    age?: number;
    skills: string[];
}

const person: Person = {
    name: 'hello world',
    age: 21
}

const actor: Actor = {
    name: 'pig',
    skills: ['dancing', 'singing', 'reading']
}

// 수정 후
// 중복되는 부분은 지워주고 extends [interface name]을 넣어준다
interface Person {
    name: string;
    age?: number;
}

interface Actor extends Person{
    // name: string;
    // age?: number;
    skills: string[];
}

 

type alias 사용해보기

위의 코드에서 interface대신 type이라고 넣어주어도 똑같은 작업이 가능하다.

// type을 사용할땐 '='을 사용한다
type Person = {
    name: string;
    age?: number;
}

// 타입 상속받을땐 타입명 '&' 넣어준다
type Actor = Person & {
    // name: string;
    // age?: number;
    skills: string[];
}

const person: Person = {
    name: 'hello world',
    age: 21
}

const actor: Actor = {
    name: 'pig',
    skills: ['dancing', 'singing', 'reading']
}
// type별칭 만들기
type People = Person[] // People이란 타입은 Person의 배열이다
const people: People = [person, actor]; // people은 People타입이고 배열안에 person과 actor을 넣을수있다

type Color = 'red' | 'orange' | 'yellow';
const color: Color = 'green'; // 에러가 뜬다.

 

💡 어떤것을 쓰던 일관성있게 사용하자

 

강의: <<벨로퍼트와 함께하는 모던 리액트>> by 강사 김민준 님