본문 바로가기

TypeScript

[TypeScript] 제네릭 방식 타입 - T에 관하여

제네릭 방식 타입은 T를 이용하여 타입을 변수화하여 사용할 수 있습니다.

const arrayLength = <T>(array: T[]): number => array.length;

const alpha = ["A", "B", "C"];
const number = [1, 2, 3, 4];

console.log(arrayLength<string>(alpha));	// 3
console.log(arrayLength<number>(number));	// 4

즉, 'arrayLength<string>(alpha)'의 T는 string이 되고 'arrayLength<number>(number)'의 T는 number가 됩니다.

 

 

다음과 같은 형식으로 타입 변수를 생략할 수 있습니다.

console.log(arrayLength(alpha));	// 3
console.log(arrayLength(number));	// 4

 

 

다음과 같이 함수 선언 시 제네릭 방식의 타입을 사용하지 않으면 any 타입으로 무엇을 입력하여도 사용이 가능합니다.

const arrayLength = (array) => array.length

const alpha = ['A', 'B', 'C']
const number = [1, 2, 3, 4];

console.log(arrayLength(alpha));	// 3
console.log(arrayLength(number));	// 3
console.log(arrayLength("abc"));	// 3
console.log(arrayLength(1234));		// undefined

 

 

하지만 제네릭 방식(T)을 이용하여 사용하면 arrayLength("abc")); 과 arrayLength(1234); 때문에 오류가 발생합니다.

const arrayLength = <T>(array: T[]): number => array.length;

const alpha = ["A", "B", "C"];
const number = [1, 2, 3, 4];

console.log(arrayLength(alpha));
console.log(arrayLength(number));
console.log(arrayLength("abc"));
console.log(arrayLength(1234));

 

 

제네릭 방식을 사용하기 위해서 반드시 T를 사용해야하는 것은 아닙니다.

다음과 같이 제네릭 방식을 V로 선언해도 상관없이 사용이 가능합니다.

const arrayLength = <V>(array: V[]): number => array.length;

const alpha = ["A", "B", "C"];
const number = [1, 2, 3, 4];

console.log(arrayLength<string>(alpha)); // 3
console.log(arrayLength<number>(number)); // 4
반응형