TypeScript를 이용해서 하는 프로젝트라 들었는데 막상 프로젝트를 시작하니 타입이 하나도 잡혀있지 않았어요
제가하는 플랫폼에서는 타입을 잡고 작업 하기로 규칙을 정했기에 다시 복습하는 마음으로 제네릭을 사용해 볼 예정이에요
제네릭은 선언 시점이 아니라 생성 시점에 타입을 명시하여 하나의 타입만이 아닌 다양한 타입을 사용할 수 있도록 하는 기법이에요
재사용성을 늘리고 동적으로 작동하기에 좀 더 효율적인 코드를 작성 할 수 있어요
// 4. generic 타입 =>
function getGeneric<MyType1, MyType2, MyType3>(arg1: MyType1, arg2: MyType2, arg3: MyType3): [MyType3, MyType2, MyType1] {
if (typeof arg1 === "number") console.log(arg1 + 1000);
return [arg3, arg2, arg1];
}
const resultGeneric = getGeneric("철수", 123, true);
// function getGeneric<string, number, boolean>(arg1: string, arg2: number, arg3: boolean): [boolean, number, string]
// 5. generic 타입 축약
function getGeneric2<T1, T2, T3>(arg1: T1, arg2: T2, arg3: T3): [T3, T2, T1] {
if (typeof arg1 === "number") console.log(arg1 + 1000);
return [arg3, arg2, arg1];
}
const resultGeneric2 = getGeneric2("철수", 123, true);
// function getGeneric2<string, number, boolean>(arg1: string, arg2: number, arg3: boolean): [boolean, number, string]
export interface ISchoolTypes<T = any> {
name: string;
class: T;
}
export interface IClassFirstTypes {
철수: {
age: number;
classNum: number;
grade: number;
hobby: string;
};
}
const res: ISchoolTypes<IClassFirstTypes> = {
name: "aaa",
class: {
철수: {
age: 15,
classNum: 1,
grade: 80,
hobby: "string",
},
},
};