// UnionfunctionprintId(id:number|string){console.log(id.toUpperCase());// if (typeof id === "string") {// // In this branch, id is of type 'string'// console.log(id.toUpperCase());// } else {// // Here, id is of type 'number'// console.log(id);// }}
// Use Genericsfunctionidentity<T>(arg:T):T{return arg;}
TypeScript
๋ณต์ฌ
โฆ
์ฐธ๊ณ : ์ฌ๊ธฐ ํํ๋ Type ๋๋ T(or U or V โฆ) ๋ ์ค์ ์๋ ์๋ฃํ(ํ์ ) ์ด ์๋๋ค. ์์ ๋กญ๊ฒ ์ง์ ํ ์ ์์ด ํ์ ๋ณ์นญ(Type Alias)๊ณผ ํผ๋ ๋ ์ ์์ง๋ง ๋ค๋ฅธ ๊ธฐ๋ฅ
โช
๊ด๋ก์ ์ผ๋ก T๋ฅผ, ๋งค๊ฐ ๋ณ์๊ฐ 2๊ฐ ์ด์์ ์ ๋๋ฆญ์ผ๋ก ํํํด์ผ ํ๋ ๊ฒฝ์ฐ์ ์ดํ๋ก๋ U, V, W ๋ฑ์ ์์ฃผ ์ฌ์ฉํ๋ค.
functionidentity<T,U>(arg1:T, arg2:U):[T,U]{return[arg1, arg2];}const result =identity(20,"Hello");// result๋ [number, string] ํ์
TypeScript
๋ณต์ฌ
โฆ
์ ํํ ๊ตฌ๋ถ ๋๋์ง ํ ์คํธ
functionisNumber(value:any){returntypeof value ==='number'&&!isNaN(value);}functionisString(value:any){returntypeof value ==='string';}// isArray๋ Array์ ๋ด์ฅ ํจ์ ์ฌ์ฉ// ๊ฐ๋จ ํ ์คํธ// givenconst testValue1:number=20;const testValue2:string="Hi";const testValue3:number[]=[1,20];// when 1const numberIdentity =identity(testValue1);// number ํ์ // then 1console.log(`Input type is : ${typeof testValue1}`);console.log(`Output type is : ${typeof numberIdentity}`);console.log(`Is number: ${isNumber(numberIdentity)}`);// true// when 2const stringIdentity =identity(testValue2);// string ํ์ // then 2console.log(`Input type is : ${typeof testValue2}`);console.log(`Output type is : ${typeof stringIdentity}`);console.log(`Is string: ${isString(stringIdentity)}`);// true// when 3const arrayIdentity =identity(testValue3);// number[] ํ์ // then 3console.log(`Input type is : ${typeof testValue3}`);console.log(`Output type is : ${typeof arrayIdentity}`);console.log(`Is array: ${Array.isArray(arrayIdentity)}`)// true