[TIL] TypeScript Interface

kiyeol·2021년 3월 15일
0

Typescript Interface?

Interface는 자바에서 클래스들이 구현해야 하는 동작을 지정하는데 사용되는 추상 자료형으로 많이 쓰였다. TypeScript에서 타입을 체크하고, 변수나 함수, 클래스에 사용된다.

예제 1)

이 코드에서 알 수 있는 내용들....

  • interface name으로 인터페이스를 지정할 수 있다.

  • implements는 Circle이라는 class가 Shape에 있어야 하는 모든 조건을 충족한다는 의미이다. 즉 Shape라는 인터페이스를 구현할 것이라고 선언하는 것이다.

  • Circle 반지름 x 반지름 x 3.14 구하는 class

  • Reacangle 직사각형 넓이x높이를 구하는 class

  • new라는 키워드는 인스턴스(객체)를 생성해주는 역할을 한다.

interface Shape {
  getArea(): number; //getArea function --> number 지정
}
class Circle implements Shape {
  constructor(private radius: number) {}

  getArea() {
    return this.radius * this.radius * Math.PI; //반지름 x 반지름 x 3.14
  }
}

class Reacangle implements Shape {
  constructor(private width: number, private height: number) {}

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

const circle = new Circle(5);
const rectangle = new Reacangle(2, 5);

const shapes: Shape[] = [circle, rectangle];


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

예제 2)

이 코드에서 알 수 있는 새로운 내용들....

  • ?가 있으면 이 인터페이스에는 age가 있을 수도 없을 수도 있다.
  • 라이브러리를 위한 type을 사용할 때는 => interface가 좋다.
  • 어떤걸 사용하든 일관성 있게 사용하는 것이 좋다.
  • type을 사용 할 경우 &는 어떤것을 상속 받는다.
  • type People = Person[] -> type People이라는 별칭은 Person의 배열이라고 할 수 있다.
  • const people: People = [person, expert]; -> people이라는 type은 People이고, 배열 안에 person, expert를 넣을 수 있다.
type Person = {
  name: string;
  age?: number;
};

//&는 Person을 상속 받는다.
type Developer = Person & {
  skills: string[];
};

const person: Person = {
  name: "김사랑",
  age: 20,
};

const expert: Developer = {
  name: "김개발",
  skills: ["javascript", "react", "typescript"],
};

type People = Person[];
const people: People = [person, expert];

type Color = "red" | "orange" | "red";
const color: Color = "orange";
profile
kyday63@gamil.com

0개의 댓글