본문 바로가기

개발에 도움이 되는/TypeScript

TypeScript 기본 (Generic)

- Generic

class, function, interface를 다양한 type으로 재사용 가능

변수 type의 변수

다른 인자가 들어가도 상관없지만 보통 T를 사용

- 기본 예제

1. function

 

function getSize<T>(arr: T[]): number {

  return arr.length;

}

 

const numArr = [1, 2, 3];

getSize<number>(numArr); // 3

 

const strArr = ['A', 'B', 'C', 'D'];

getSize<string>(strArr); // 4

 

// generic으로 선언하면 굳이 타입 지정해주지 않아도 알아서 판단하긴 함

const boolArr = [false, true, false];

getSize(boolArr); // 3

 

 

2. interface

 

interface Item<T> {

  name: string;

  price: number;

  option: T;

}

 

// object 대신 실제 object로 선언해도 된다. object => { color: string; navi: boolean } 가능

const A: Item<object> = {

  name: "car",

  price: 2000,

  option: {

    color: "blue",

    navi: true,

  },

};

 

const B: Item<string> = {

  name: "car",

  price: 1000,

  option: "normal" 

};

 

 

- 응용

 

interface A {

  name: string;

  age: number;

}

 

interface B {

  name: number;

  color: string;

}

 

interface C {

  price: numberl

}

 

const a: A = { name: 'a', age: 31 };

const b: B = { name: 3000, color: "purple" };

const c: C = { price: 5000 };

 

// data는 T의 type인데 T는 string type의 name을 가지고 있는 T

function showName<T extends { name: string }>(data: T): string{

  return data.name;

}

 

showName(a);

showName(b); // name type이 number라서 error

showName(c); // name이 없기 때문에 error

 

 

 

 

 

 

반응형