function helloGeneric<**T**>(message: **T**): **T** {
return message
}
helloGeneric<string>('Lee')
helloGeneric<>('Lee') // T가 인수에 의해서 알아서 추론됨
- T 자리에 다양한 데이터 타입이 할당될 수 있다.
- 제네릭 함수를 실제로 사용할 때, T 자리를 비워 두면 제네릭 함수로 들어 오는 인수의 타입을 통해 T를 추론한다.
Generic Array
function helloArray<T>(message: **T[]**): T {
return message[0]
}
- 제네릭 배열인 T[]을 매개변수로 설정한 함수
- 만약 T[] 배열의 요소의 타입이 두 개 이상이면 T는 union 타입을 가지게 된다.
Generic Tuple
function helloTuple<T, K>(message: [T, K]): T {
return message[0] // T 타입이 반환된다.
}
- 튜플의 요소는 타입이 두 개 이상이지만 배열과 다르게 하나의 타입만 반환된다.
Generic의 상속
class PersonExtends<**T extends string | number**> {
private _name: T
constructor(name: T) {
this._name = name
}
}
new PersonExtends('Lee')
new PersonExtends(39)
new PersonExtends(true) // string or number가 아니므로 오류
- extends 키워드를 통해 T의 범위를 제한할 수 있다.
keyof
function prop<T, **K extends keyof T**>(obj: T, key: K, value: T[K]): void {
obj[key] = value
}