[TIL]220503 - typeScript(Generics)

koseony·2022년 5월 3일

TIL(Today I Learn)

목록 보기
10/19
post-thumbnail

generic

아래와 같이 코딩하면 어떤 변수든 다 any가 된다.

any는 들어오는 input에 의해 달라지는 타이핑을 할 수 없다.
그래서 generic을 사용해서 그에 맞는 타입을 설정해준다.

1. generic 문법

generic문법

function helloBasic<T>(message: T): T {
  return message;
}

helloBasic<string>('kwak');   //직접 넣어주기
helloBasic(21);   //추론
function helloBasic<T, U>(message: T, comment: U): T {
  return message;
}

helloBasic<string, number>('kwak', 31);   //직접 넣어주기
helloBasic(21, 31);   //추론
  • 직접 넣어주면 넣어준 타입으로 체크
  • 넣어주지 않으면 추론

2. generic array & tuple

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

helloArray(['hello', 'world']);
helloArray(['hello', 5]); //string | number 유니온 타입이 된다.

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

helloTuple(['hello', 'world']);
helloTuple(['hello', 5]);   //string

array와 tuple을 잘 구분해서 사용해야한다.

3. generic function

함수의 타입만 선언하기

4. generic class

클래스에 제네릭 선언하고 사용하기

class Person<T> {
  private _name: T;

  constructor(name: T) {
    this._name = name;
  }
}

new Person('kwak');
class Person<T, K> {
  private _name: T;
  private _age: K;

  constructor(name: T, age: K) {
    this._name = name;
    this._age = age;
  }
}

new Person('kwak', 31);
new Person<string, number>('kwak', 'kwak'); //error

5. generic extends

extends를 generic과 함께 사용하면 상속과는 약간 다르다.

class PersonExtends<T extends string | number> {
  private _name: T;

  constructor(name: T){
    this._name = name;
  }
}

// T 는 string과 number만 가능하다

new PersonExtends('kwak');
new PersonExtends(31);
new PersonExtends(true);  //'boolean' 형식의 인수는 'string | number' 형식의 매개 변수에 할당될 수 없습니다.ts(2345)

generic을 쓸때 extends를 쓴다면 좀더 명확하게 할 수 있다.

6. keyof & type lookup

profile
프론트엔드 개발자

0개의 댓글