[타입스크립트 (4)] Generic

SeHoony·2021년 9월 24일
1

TypeScript

목록 보기
4/7
post-thumbnail

1. 개념

Generic은 Type 보장재사용성 면에서 탁월하다. 예를 들어, function anyMethod(num : number){}함수는 parameter로 숫자만 쓸 수 있다. 그러나 Generic은 숫자가 들어가는 자리에 string, object, array, null, undefined, boolean 등등 어떤 것이든 넣을 수 있도록 한다.
즉, 숫자만 가능한 일을 모두가 가능한 일, 일반적인 일로 만든다. Generic을 번역하면 "일반화"이다.

2. Function 활용

parameter값이 string이면 "조용히 하자"가 출력된다. 그 외에 donSpeak에는 어떤 type이 들어와도 "조용히 하자"가 출력되지 않는다.

function dontSpeack<T>(noise: T | string) {
    if (typeof noise == "string") {
      console.log("조용히 하자")
    }
    return typeof noise
  }

3. Class 활용

이 예제는 쓰레기인 거 같다. 하지만 class에 어떻게 generic을 써보면 좋을까 생각해봤는데 참고만 하면 좋을 거 같다! 더 나은 예제가 떠오르면 수정해봐야지

class Login<T1, T2> {
  private static database = {
    id: "sehoon",
    pwd: 1234,
  }
  constructor(private id: T1, private pwd: T2) {}

  match(did, dpwd): boolean {
    if (did == this.id && dpwd == this.pwd) {
      return true
    }
    return false
  } 

4. Constraint(조건부 Generic)

키워드는 'extends'이다. 이를 이용하여, parameter의 generic type의 범위를 좁힐 수 있다. 좁히는 이유는 예제 코드를 통해 밝힌다.

interface athlete {
    exercise: () => void
  }

  class runner implements athlete {
    run() {}
    exercise() {
      console.log("running...")
    }
  }

  class Swimmer implements athlete {
    swim() {}
    exercise() {
      console.log("swimming...")
    }
  }

  function exercise<T extends athlete>(athlete: T) {
    // Generic type에서 exercise()함수를 쓸 수 있는 이유는,
    // type의 범위를 athlete로 좁혀놓았기 때문이다.
    athlete.exercise()
    return athlete
  }
profile
두 발로 매일 정진하는 두발자, 강세훈입니다. 저는 '두 발'이라는 이 단어를 참 좋아합니다. 이 말이 주는 건강, 정직 그리고 성실의 느낌이 제가 주는 분위기가 되었으면 좋겠습니다.

0개의 댓글