TIL DAY.52 [React + Typescript] interface, type alias , generics

Dan·2021년 4월 28일
0

TypeScript

목록 보기
3/3
post-thumbnail

인터페이스(Interface)

인터페이스는 클래스 또는 객체를 위한 타입을 지정할 때 사용 됩니다.

아래는 Shape이라는 인터페이스를 통해 Circle 과 Rectangle의 class타입을 지정해줬습니다.

interface Shape {
  getArea(): number;
}

//public으로 constructor을 지정해주면 어느 곳에서든 지정한 변수를 불러올수 있습니다.
//private으로 설정하게 되면 지정된 class안에서만 사용 할 수 있습니다
class Circle implements Shape {
  constructor(public radius: number) {}
  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);
const shapes: Shape[] = [circle, rectangle];

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

아래는 Person과 Developer 인터페이스를 통해 객체의 타입을 지정해줬습니다.

interface Person {
  name: string;
  age?: number;
}
//?를 통해서 객체에 age라는 값이 없어도 출력 될 수 있도록 만들 수 있습니다.
interface Developer extends Person {
  skills: string[];
}
// extends를 통해서 Person의 인터페이스를 상속 받을 수 있습니다.
const person: Person = {
  name: "김사람",
  age: 5
};

const expert: Developer = {
  name: "김개발",
  skills: ["김존", "나는"]
};

타입엘리어스(Type Alias)

Alias라는 말은 별칭이라는 뜻입니다. 그래서 type에다가 별칭을 달아주는게 type alias입니다. 위와 똑같은 예제를 type alias를 통해서 구현했습니다. 간단하게 interface를 type으로 바꿔주고 extends 를 &로 대체했습니다.

type Person = {
  name: string;
  age?: number;
};

type Developer = Person & {
  skills: string[];
};

const person: Person = {
  name: "김사람",
  age: 5
};

const expert: Developer = {
  name: "김개발",
  skills: ["김존", "나는"]
};

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

type Color = "red" | "orange" | "yellow";
const color: Color = "orange";
  • 라이브러리를 위한 타입을 설정할때는 interface를 쓰는 것을 권장합니다. 그 외에는 type을 쓰는 것이 더 편리합니다.

제너릭스(Generics)

타입스크립트에서 함수 클래스 인터페이스 또는 타입 엘리어스를 사용하게 될 때 여러종류의 타입에 대해서 호환을 맞추어야할 때 사용되는 문법입니다.

function merge<T1, T2>(a: T1, b: T2) {
  return {
    ...a,
    ...b
  };
}

const merged = merge({ foo: 1 }, { bar: 2, foobar: 3 });
// 타입을 any나 object로 설정 할 수 도 있지만 제너릭스를 사용해서 실제 파라미터로 넣는 타입을 유추 시킬 수 있습니다.

인터페이스에서 제너릭스를 사용하는 예제입니다.


interface Items<T> {
  list: T[];
}

const itmes: Items<string, number> = {
  list: ["a", "b", "c"],
  value: 123
};

타입 엘리어스에서 제너릭스를 사용하는 예제입니다.


type Items<T, V> = {
  list: T[];
  value: V;
};
const itmes: Items<string, number> = {
  list: ["a", "b", "c"],
  value: 123
};

마지막으로 클래스에서 제너릭스를 사용해보는 예제입니다.

class Queue<T> {
  list: T[] = [];

  get length() {
    return this.list.length;
  }

  enqueue(item: T) {
    this.list.push(item);
  }

  dequeue() {
    return this.list.shift();
  }
}

const queue = new Queue<Number>();
queue.enqueue(0);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);

while (queue.length > 0) {
  console.log(queue.dequeue());
}
profile
만들고 싶은게 많은 개발자

0개의 댓글