-
[Typescript] 제네릭(Generic) 메서드 작성웹 개발/소소한 팁, 버그 해결 2024. 3. 20. 00:59
제네릭(Generic)은 여러 가지 타입에서 동작하는 컴포넌트를 생성하는데 사용되는데, 이를 활용하면 재사용성이 높은 컴포넌트를 만들 수 있다. 일반적으로 아래와 같이 작성하며, 함수 사용 시 같이 넘겨준 모든 타입 T에 대해 동작한다.
function genericFunctionName<T>(arg: T): T { // Do something return arg; }
코드를 작성하다보면 arrow function ("=>" 이용하는) 형태로 사용해야 할 때도 있는데, 그럴 땐 아래와 같이 작성한다.
const genericArrowFunctionName = <T,>(x: T) => { // Do something retrun x; };
조금 더 확장하면 아래와 같이 제네릭 타입(인터페이스)이랑 제네릭 클래스도 작성할 수 있다.
interface GenericInterface { <T>(data: T): T; } function genericDataFunction<T>(data: T): T { return data; }
class GenericData<T> { value: T; sum: (x: T, y: T) => T; } let math = new GenericData<number>();
물론 아래와 같이 확장도 가능하다.
function logText<T>(text: T[]): number { return text.length; }
interface TextWise { text: string; } function genericGetText<T extends TextWise>(arg: T): T { return arg.text; }
더 자세한 내용은 Documentation 참고.
Documentation - Generics
Types which take parameters
www.typescriptlang.org
끗~
'웹 개발 > 소소한 팁, 버그 해결' 카테고리의 다른 글
[CSS] 간단한 아이콘 회전 애니메이션 [Tailwind CSS] (0) 2024.03.20 [CSS] icon 회전하기 / <i> 태그 회전하기 [Tailwind CSS] (0) 2024.03.20 [Typescript] TypeError: Webpack imported module is not a function 해결 (0) 2024.03.20 [Next.js 14] 버튼 동시에 눌리는 현상 막기 [stopPropagation][Typescript] (0) 2024.03.20 [Next.js] 비교 연산자로 날짜 비교 안 될 때 [JavaScript] (0) 2024.03.15