7-1. Generic Type Variable and Generic Function

/* Generics */
function func<T>(value: T): T {
  return value;
}

let num = func(10);
num.toFixed();
// num.toUpperCase(); // error

let str = func("string");
str.toUpperCase();

let bool = func(true);

// explicit typing
let arr = func<[number, number, number]>([1, 2, 3]);
// 타입 단언을 이용할수도 있다. 
let arr2 = func([1, 2, 3] as [number, number, number]);

Syntax

Generic Function 호출시 Explicit하게 타입 지정하는 방법

7-2. 제네릭 타입 변수 응용하기(함수에서)

두개 이상의 타입 변수 사용하기

/* multiple type variables */
function swap<T, U>(a: T, b: U) {
  return [b, a];
}
const [a, b] = swap("1", 2);

배열, 튜플로 사용하기

/* type variable for array element */
function returnFirstValue<T>(arr: T[]){
  return arr[0];
}
let num = returnFirstValue([1, 2, 3]);

/* type variable for tuple */
function returnFirstValue2<T>(arr: [T, ...unknown[]]){
  return arr[0];
}
let num2 = returnFirstValue2([1, "2", false]);

extends 키워드 사용하여 조건 달기