끄적끄적 메모장
[TypeScript] 함수(function)에 대해서 알아보자! 2 본문
다음으로 좀더 간단하게 표현할 수 있는 TypePlaceholder에 대해서 알아보자.
코드로 가기전 Concrete 타입과 Generic 타입에 대해서 알아보도록 하자,
Concrete 타입이란?
1) number, boolean, string, void, unknown 같은 많이 사용하였던 타입들을 말합니다.
Generic 타입이란?
1) Generic 이란 타입을 마치 함수의 파라미터처럼 사용하는 것을 의미합니다.
2) 정적 type언어는 클래스나 함수를 정의할 때 type을 선언해야 합니다.
3) Generic은 코드를 작성할 때가 아니라 코드를 수행될 때 (런타임) 타입을 명시합니다.
4) 코드를 작성할 때 식별자를 써서 아직 정해지지 않은 타입을 표시합니다. (일반적으로 T, U, V ...를 사용)
type SuperPrint = {
(arr: number[]): void;
(arr: boolean[]): void;
(arr: string[]): void;
(arr: (number | boolean)[]): void;
};
const superPrint: SuperPrint = (arr) => {
arr.forEach((i) => console.log(i));
};
superPrint([1, 2, 3, 4]);
superPrint([true, false, true]);
superPrint(["a", "b", "c"]);
superPrint([1, 2, true, false]);
위 코드와 같이 각각 타입을 표현하는 방법이 있습니다. 하지만 해당 코드는 Concrete 타입으로 표현하였습니다.
Concrete 타입 대신에 Generic 타입을 받게 된다면 보다 더 깔끔한 코드를 만들 수 있다. 아래에 예시가 있습니다.
type SuperPrint = {
<TypePlaceholdar>(arr: TypePlaceholdar[]): TypePlaceholdar;
};
const superPrint: SuperPrint = (arr) => arr[0];
superPrint([1, 2, 3, 4]);
superPrint([true, false, true]);
superPrint(["a", "b", "c"]);
superPrint([1, 2, true, false, "33"]);
위 코드처럼 리팩토링을 할 수 있습니다.
여기서 Generic 사용 예시중 하나인 <TypePlaceholdar>는 타입을 일일이 적지 않아도 그것이 뭔지 추론하여 함수가 정상적으로 실행되게 도와줍니다.
type SuperPrint = {
<T, M>(a: T[], b: M): T;
};
const superPrint: SuperPrint = (a) => a[0];
const aa = superPrint([1, 2, 3, 4], "x");
const bb = superPrint([true, false, true], []);
const cc = superPrint(["a", "b", "c"], 2);
const dd = superPrint([1, 2, true, false], "Hi");
위 코드에서 2개의 Generic 타입을 표현한 코드입니다. 2개를 표현할때는 <T, M> 과 같이 코딩하며 추측하여 각각 타입에 맞는 함수를 선언해줍니다.
위 이미지와 같이 추측하여 올바른 타입으로 표시해줍니다.
type Players<E> = {
name: string;
extraInfo: E;
};
type NicoExtra = {
favFood: string;
};
type NicoPlayer = Players<NicoExtra>;
const bg: NicoPlayer = {
name: "bg",
extraInfo: {
favFood: "kimchi",
},
};
const mj: Players<null> = {
name: "mg",
extraInfo: null,
};
위 코드처럼 Player<E> 제네릭 요소 있는 경우가 있습니다.
만약 내가 많은 것들이 있는 큰 타입을 하나 가지고 있는데, 그 중 하나가 달라질 수 있는 타입이라면 그곳에 제네릭을 넣어주면 됩니다. 그렇게 된다면 그 타입을 많은 곳에서 재사용을 할 수 있게 됩니다. 또한 커스텀한 타입에서 사용이 가능합니다.
이처럼 제네릭은 강력합니다.
'프론트엔드 > TypeScript' 카테고리의 다른 글
[TypeScript] Interface에 대해서 알아보자 (0) | 2023.05.23 |
---|---|
[TypeScript] Public, Private, Protected에 대해서 알아보자 (0) | 2023.05.17 |
[TypeScript] 함수(function)에 대해서 알아보자! (0) | 2023.05.16 |
[TypeScript] 기본 문법 알아보기 2 (0) | 2023.05.15 |
[TypeScript] TypeScript 활용하여 HTML 구현해보기 (0) | 2023.05.12 |