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

any는 들어오는 input에 의해 달라지는 타이핑을 할 수 없다.
그래서 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); //추론
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을 잘 구분해서 사용해야한다.
함수의 타입만 선언하기

클래스에 제네릭 선언하고 사용하기
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
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를 쓴다면 좀더 명확하게 할 수 있다.
