제네릭 · 타입 매개변수
입력과 출력의 타입 관계를 유지하면서 함수를 재사용합니다.
기본 문법
function first<T>(items: T[]): T | undefined작은 예제 typescript
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([10, 20]));
console.log(first(["apple", "pear"]));실행 결과
10 apple
헷갈리기 쉬운 점
- 아무 값이나 허용하는 any와 달리 호출할 때 결정된 타입 관계를 유지합니다.
- 빈 배열이면 undefined가 나올 수 있습니다. 반환 타입에도 그 가능성을 표시하세요.