function printArray(arr: number[]): void {
console.log(arr);
}
const arr1 = [10, 20, 30];
printArray(arr1);
function printArray(arr: number[] | string[]): void {
console.log(arr);
}
const arr2 = ["a", "b", "c"];
printArray(arr2);
function printArray(arr: number[] | string[] | boolean[]): void {
console.log(arr);
}
const arr3 = [true, false, true];
printArray(arr3);
예) 하나의 코드로 숫자, 문자열 등 처리 가능

function 함수이름<T>(매개변수: T타입): 반환값타입 {
// 코드
}
function printArray<T>(arr: T[]): void {
console.log(arr);
}
const InterfaceGeneric = () => {
interface UserInterface {
name: string;
age: number;
phone: number | string
}
const user1: UserInterface = {
name: "soo",
age: 20,
phone: "82-10-1234-5678"
};
const user2: UserInterface = {
name: "park",
age: 30,
phone: 821012345678
};
return <div></div>;
};
export default InterfaceGeneric;
const InterfaceGeneric = () => {
interface UserInterface<T> {
name: string;
age: number;
phone: T;
}
const user1: UserInterface <string> = {
name: "soo",
age: 20,
phone: "82-10-1234-5678",
};
const user2: UserInterface <number> = {
name: "park",
age: 30,
phone: 821012345678,
};
return <div></div>;
};
export default InterfaceGeneric;
const ClassGeneric = () => {
class User<T> {
constructor(public name: string, public age: number, public phone: T) {}
}
const user1: User<number> = new User("soo", 20, 821012345678);
const user2: User<string> = new User("soo", 20, "82-10-1234-5678");
return <div></div>;
};
export default ClassGeneric;