TypeScript _ Generics

LOOPY·2021년 8월 19일
post-thumbnail

1. Generics

  • C에서 배웠던 Template랑 똑같네!
function helloGeneric<T>(message: T): T{
  return message;
}
  
helloBasic<string>(39); // error
helloBasic<string>(“Mark”); 
helloBasic(36); // T는 자동으로 추론됨

2. Generics Array & Tuple

function helloArray<T>(message: T[]): T{
  return message[0];
}

helloArray([“Hello”, “World”]);
helloArray([“Hello”, 7]);

function helloTuple<T, K>(message: [T, K]): T{
  return message[0];
}

helloTuple([“Hello”, “World”]);
helloTuple([“Hello”, 7]);
  • 여러 개는 <T, U> 꼴로 사용

3. Generics Function

type HelloFunctionGeneric1 = <T>(message: T) => T;
const helloFunction1: HelloFunctionGeneric1 = <T>(message: T): T => {
  return message;
}

interface HelloFunctionGeneric2{
  <T>(message: T): T;
}
const helloFunction2: HelloFunctionGeneric2 = <T>(message: T): T => {
  return message;
}

4. Generics Class

class Person<T>{
  private _name: T;
  constructor(name: T){
    this._name = name;
  }
}
new Person(“Mark”);

5. Generics with extends

class PersonExtends<T extends string | number>{ 
// T는 string과 number만 가능
  private _name: T;
  constructor(name: T){
    this._name = name;
  }
}

6. Keyof & type lookup system

interface IPerson{
  name: string;
  age: number;
}
const person: IPerson = {
  name: “Mark”,
  age: 39,
}

function getProp<T, K extends keyof T>(obj: T, key: K): T[K]{
  return obj[key];
}
getProp(person, “age”);

function setProp<T, K extends keyof T>(obj: T, Key: K, value: T[K]): void{
obj[key] = value;
}
setProp(person, “name”, “Anna”);

-> string | number 형태로 union type 이용하지 않아도 돼 더욱 안전

profile
2년차 프론트엔드 개발자의 소소한 기록을 담습니다 :-)

0개의 댓글