[TypeScript] type alias와 interface

손종일·2020년 11월 28일
0

TypeScript

목록 보기
1/4
post-thumbnail

TypeScript

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

Interface 사용 방법

// Shape이라는 객체의 타입을 지정하기 위하여 interface 사용
interface Shape {
  // getArea()의 값은 숫자
  getArea(): number;
}

// implements: Circle은 Shape 인터페이스 안에 있는 조건을 충족해야한다.
class Circle implements Shpae {
  radius: number;
}

위의 코드처럼 구성하면 Circle에 빨간줄이 생기게 되는데 이니셜라이즈가 없고, 생성자가 없다는 오류가 생긴다.
-> 아래의 코드처럼 constructor를 구현하면 된다.

interface Shape {
  // getArea()의 값은 숫자
  getArea(): number;
}

class Circle implements Shpae {
  radius: number;
// 인자의 타입을 숫자로 지정
  constructor(radius: number) {
    this.radius = radius;
  }

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

public or private를 사용하여 자동적으로 class안에 인식시킬 수 있다.

public : circle. ~ 뒤에 안에 들어가는 내용 조회 가능
private : circle. ~ 뒤에 안에 들어가는 내용 조회 불가

interface Shape {
  getArea(): number;
}

class Circle implements Shpae {
  //public or private를 사용하면 자동으로 class 안에 인식시킬 수 있다.
  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;
  }
}

const circle = new Circle(5);
const rectangle = new Rectangle(2,5);
const shapes: Shape[] = [circle, rectangle]

shapes.forEach(shapes => {
  console.log(shapes.getArea());
})
// 78.53~
// 10

Optional Chaining의 사용 방법을 알아보자

우리가 리액트에서 많이 다루던 내용인 Optional Chaning은
예를 들어, 서버에서 응답을 받기 전에 undefined or null일 경우에는 && 라는 이용할 수도 있지만, 코드의 복잡도가 올라갈수록 코드는 길어지고 가독성은 떨어지게 됩니다.
이럴 경우에는 Optional Chaining을 사용하여 쉽게 해결이 가능합니다.
좌측에 값이 undefined거나 null인지 확인하고, 해당한다면 이후에 값을 찾는 것을 중지하고 undefined를 반환합니다.

interface Person {
  name: string;
  // 변수 뒤에 ?를 넣어주면 age라는 값이 있을수도, 없을 수도 있다라는 뜻이다.
  age?: number;
}

// Person이라는 값을 가져온 후, skills 문자형 배열 추가
interface Developer extends Person{
  skills: string[];
}

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

const expert: Developer = {
  name: "개비",
  skills: ['바보', '멍청이']
}

Type Alias (클래스 또는 객체를 위한 타입을 지정할 때 사용하는 문법)

Type Alias 사용 방법 ( 위의 코드를 그대로 Alias로만 변경하였다.)
Alias를 사용하면 interface에서 사용하지 못하는 별칭을 지어줄 수 있다.

// type을 사용하여 Alias 문법으로 변경
type Person {
  name: string;
  // 변수 뒤에 ?를 넣어주면 age라는 값이 있을수도, 없을 수도 있다라는 뜻이다.
  age?: number;
}

// Person이라는 값을 가져온 후, skills 문자형 배열 추가
type Developer extends Person{
  skills: string[];
}

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

const expert: Developer = {
  name: "개비",
  skills: ['바보', '멍청이']
}

// People이라는 별칭 생성
type People = person[];
const people: People = [person, expert];

console.log(people)

Type Alias를 사용해야하는지 Interface를 사용해야하는지 잘 생각해야합니다.
두가지 타입 중 일관성이 있도록 한가지만 사용하는 것이 좋습니다.
또한, 공식문서에서는 라이브러리를 사용할때는 인터페이스를 쓰는 것을 권장하고 있습니다.

profile
Allday

0개의 댓글