내일배움캠프 노드 4기/Today I Learned

[TypeScript] Generic types - 2

Milb 2023. 1. 27. 19:51

제네릭 : 선언 시점이 아닌 생성 시점에 타입을 명시하여 하나의 타입만이 아닌 다양한 타입을 사용할 수 있도록 하는 기법

 

제네릭 선언 시 관용적으로 사용하는 식별자

  • T
  • U
  • V

함수

/types/index.ts

export type User = {
  email: string;
  name: string;
};

export enum Status {
  Initiated = "Initiated",
  Pending = "Pending",
  Shopped = "Shopped",
  Delivered = "Delivered",
}

export interface Order {
  buyer: string;
  orderStatus: Status;
}

 

function.ts - values, keys

// enums
import { Status } from "../types";

// types
import type { Order, User } from "../types";

function getData<T>(data: T): T {
  return data;
}

console.log(getData<string>("string data"));
console.log(getData<number>(1234));
console.log(getData<User>({ email: "abc123@gmail.com", name: "cathy" }));
console.log(getData<string[]>(["string", "data"]));
console.log(getData<string[]>([]));

const orders: Order[] = Object.values<Status>(Status).map((status, index) => {
  return {
    buyer: `buyer #${index}`,
    orderStatus: status,
  };
});

 

 

클래스

// public, private, protected

// public => 제한 없음, 누구나 access 가능
// private => 특정 class 안에서만 access 가능
// protected => 특정 class 안에서 access 가능, 상속받는 class 안에서 access 가능

class Base {
  first = "";
  public second = "";
  protected third = "";
  private fourth = "";

  baseFunction() {
    this.fourth;
  }
}

class Inherited extends Base {
  myFunction() {
    this.first;
    this.second;
    this.third;  // 상위클래스에서 protected라 사용 가능
    // this.fourth; 상위클래스에서 private라 오류 발생
  }
}

const inherited = new Inherited();

inherited.first;
inherited.second;
// inherited.third;  // protected라 클래스 밖에서 사용 불가능
// inherited.fourth; // private라 클래스 밖에서 사용 불가능