Development Study/Frontend

[TypeScript] TypeScript Grammar - 09

  • -
728x90

Previous Series

 

[TypeScript] TypeScript Grammar - 08

Previous Series [TypeScript] TypeScript Grammar - 02 Previous Series [TypeScript] TypeScript Grammar - 01 1. Type Annotation TypeScript uses colon ( : ) behind variables to annotate a type const myMaxHamburger: number = 3; const answer: string = "Yes I can

time-map-installer.tistory.com


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
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.