Generic

파라미터로 타입을 입력할 수 있는 함수를 생성할 수 있다.

 

function 함수<Type>( x: Type[] ) : Type{
	return x[0];
}

let a = 함수<number>([4,2]);
let b = 함수<string>(['4','2']);
console.log(a); // 4 ( number )
console.log(b); // '4' ( string )

 

Generic Type 제한

아래와 같이 함수의 타입이 extends된 속성을 가지고 있는지를 확인

커스텀 타입으로도 타입파라미터 제한이 가능하다.

function 함수<Type extends number>( x: Type[] ) : Type{
	return x[0];
}

let a = 함수<number>([4,2]);

console.log(a); // 4 ( number )

 

interface LengthCheck {
	length : number
}

function 함수<Type extends LengthCheck>( x: Type[] ) : Type{
	return x.length;
}

let a = 함수<string[]>(['100']);

console.log(a); // 1
728x90

+ Recent posts