Development Study/Frontend
[TypeScript] TypeScript Grammar - 09
TMInstaller
2023. 1. 8. 18:15
728x90
Previous Series
9. Generic
If you use generic, you can recycle classes or interface to many types
When you declatate it, just write the parameters and decide types when it starts
function getSize<T>(arr: T[]): number {
return arr.length;
}
const arr1 = [1, 2, 3];
getSize(arr1);// 3
getSize<number>(arr1);
const arr2 = ["a","b","c"];
getSize(arr2);// 3
getSize<string>(arr2);// 3
const arr3 = [false , true , true];
getSize(arr3);// 3
const arr4 = [{}, {},{name:"Tim"}];
getSize(arr4);// 3
9_01. Generic_interface
interface Macbook<T> {
name: string;
price: number;
option: T;
}
const m1 Macbook<object> = {
name: "m1 air",
price: 1500000,
option:
{
color: "silvergray",
coupon: false,
},
}
const m2 Macbook<string> = {
name: 'm2 air',
price: 1800000,
option: "not bad",
}
End
728x90