typescript interface

jangdu·2022년 10월 27일
0

typescript

목록 보기
3/16

interface

클래스나 객체를 위해 타입을 지정할 때 사용

특정한 조건을 가지는 클래스를 명시하고 싶을 때 interface를 사용해 조건을 설정

클래스 선언 시 implements키워드를 사용해 해당 클래스가 interface의 조건을 구현함을 명시

// Shape이란 interface
interface Shape {
    // 리턴값이 숫자인 getArea()함수가 필수
    getArea(): number;
}

// implements: shape interface 조건 충족을 명시
class Circle implements Shape{
    
    radius: number; // 멤버변수 radius 값 설정

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

    // 넓이를 가져오는 함수 구현
    getArea(): number {
        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(): number {
        return this.width * this.height;
    }
}

const shapes: Shape[] = [new Circle(5), new Rectangle(10, 5)];
console.log(shapes[0].getArea());
console.log(shapes[1].getArea());

public private accessor

위 코드 constructor에서 값 하나하나 설정했는데 typescript에서는 constructor의 파라미터 쪽에 public, private accessor를 사용하면 하나하나 설정하는 작업이 생략 가능하다.

일반객체 interface

interface Person {
    name: string;
    age?: number;   // ?: 설정을 해도되고 안해도 됨
}
interface Developer {
    name: string;
    age?: number;
    skills: string[];
}

const person: Person = {
    name: '두두',
    age: 20
};

const developer: Developer = {
    name: 'doho',
    skills: ['js', 'react']
};

일반객체를 interface를 이용해 타입을 지정하는 법

위의 코드처럼 유사한 형태에서 extends를 이용해 상속 가능

interface Person {
    name: string;
    age?: number;   // ?: 설정을 해도되고 안해도 됨
}
interface Developer extends Person {
    skills: string[];
}

const person: Person = {
    name: '두두',
    age: 20
};

const developer: Developer = {
    name: 'doho',
    skills: ['js', 'react']
};
profile
대충적음 전부 나만 볼래

0개의 댓글