[TIL #41 기업 협업] interface

Whoyoung90·2021년 4월 19일
0
post-thumbnail

210419 WECODE #41 기업협업 6일차

리액트 프로젝트에서 타입스크립트 사용하기

오늘 타입스크립트를 처음 공부해 보았고
그 중에서 오늘 익혀본 interface에 대해 작성해보겠다.

  • pratice.ts 파일에 코드를 작성하고 터미널에 tsc 명령어를 입력하면
    dist 디렉터리에 practice.js파일이 생성된다.
    (우리가 tsconfig.json파일에 경로를 지정한 "outDir": "./dist")

  • 다음엔, node dist/practice 명령어를 입력하여 컴파일된 스크립트를 실행시켜 볼 수 있다.

> interface 사용해보기

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

  1. 클래스에서 interface 를 implements 하기

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

> 클래스에서 interface 를 implements 하기

interface Shape { 
  getArea(): number;
}
  • Shape 라는 interface 를 선언
  • Shape interface 에는 getArea 라는 함수가 꼭 있어야 하며 해당 함수의 반환값은 숫자임을 의미한다.
class Circle implements Shape {
  constructor(public radius: number) {
    this.radius = radius;
  } 

  getArea() {
    return this.radius * this.radius * Math.PI; 
  } // 너비를 가져오는 함수를 구현
}
  • implements 키워드를 사용하여 해당 클래스가 Shape interface 의 조건을 충족하겠다는 것을 명시한다.
  • 멤버 변수 radius 값을 설정
  • Math.PI은 원의 둘레와 지름의 비율, 약 3.14
class Rectangle implements Shape {
  constructor(private width: number, private height: number) {
    this.width = width;
    this.height = height;
  }

  getArea() {
    return this.width * this.height;
  }
}
  • public 으로 선언된 값은 클래스 외부에서 조회 할 수 있으며

  • private 으로 선언된 값은 클래스 내부에서만 조회 할 수 있다.

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

const circle = new Circle(5);
const rectangle = new Rectangle(10, 5);

console.log(circle.radius);
console.log(rectangle.width); //error!

const shapes: Shape[] = [new Circle(5), new Rectangle(10, 5)];

shapes.forEach((el) => {
  console.log(el.getArea());
});
  • console.log(rectangle.width); => ERROR!!
    private width값은 클래스 외부에서 조회할 수 없기 때문이다!

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

interface Person {
  name: string;
  age?: number;
}
interface Developer extends Person {
  skills: string[];
}
  • ?는 설정을 해도 되고 안해도 되는 값이라는 것을 의미
  • 형태가 유사할 땐 다른 interface 를 extends 를 사용해서 상속받을 수 있다.
const person: Person = {
  name: "김사람",
  age: 20,
};

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

const people: Person[] = [person, expert];
profile
비전공으로 일식 쉐프가 되었듯, 배움에 겸손한 프론트엔드 개발자가 되겠습니다 :)

0개의 댓글