-
3월 23일 TIL : TS-Overloading, Polymorphism [타입스크립트야... 내가 명시도안했는데 타입을 유추한거야?]Java Script & Type Script/TIL 2023. 3. 24. 00:25728x90
Overloading
오버로딩은 함수가 서로 다른 여러개의 call signature를 갖고있을 때 발생한다.
type Add= (a: number, b: number)=> number const add: Add = (a, b) =>a+b
type Add= (a: number, b: number)=> number 위 callsignature는 아래 callsignature와 같다. type Add= { (a: number, b: number) : number }
1. 매개변수의 데이터 타입이 다른 경우 예외 처리
type Add= { (a: number, b: number) : number (a: number, b: string) : number } const add: Add = (a, b) => a+b
위 코드 실행시 발생하는 ts에러.
b가 number일 수도 있고 string일 수도 있기때문에 a+b가 불가능하다
const add3: Add3 = (a, b) => { if (typeof b === "string") return a; return a + b; };
이렇게해주면 에러가 사라짐.
2. 매개변수의 수가 다른 경우 예외 처리
type Add2 = { (a: number, b: number): number, (a: number, b: number, c: number): number } const add2: Add2 = (a, b, c) => { return a + b; }
매개변수가 a와b와c 모두가 될 수 있고 또, a와b만일 수도 있다. 즉, c는 optional.
이 코드는 에러가 발생한다. return은 a+b이지만, c를 매개변수로 갖고있어서 c를 return에서 연산하지 않아도 아래같이 에러가발생.
const add2: Add2 = (a, b, c?: number) => { if (c) return a + b + c; return a + b; };
c가 optional임을 명시해주고 if로 예외처리해주면 더이상 에러안남.
(위와 같은 함수는 거의 없지만 외부 라이브러리에서 활용될 수 있다
Polymorphism
한국말로하면 다형성
❓poly란?
- many, serveral, much, multi 등과 같은 뜻
❓morphos란?
- form, structure 등과 같은 뜻
❗polymorphos = poly + morphos = 여러 다른 구조!concrete type : number, boolean, void 등 지금까지 배운 타입
generic type : 타입의 placeholder
callSignature를 작성하는데 concrete type을 알 수 없을 때 generic이용1. 배열을 받아서 그 배열의 요소를 각각 콘솔로그로 찍는 함수 superPrint
type SuperPrint = { (arr:number[] ):void (arr:boolean[]):void } const superPrint: SuperPrint=(arr)=>{ arr.forEach(i=>console.log(i)) } superPrint([1,2,3,4]) superPrint([true,false,true]) //이 위까진 에러없는데, 아래에서 타입으로 지정하지않은 string타입으로 배열을 보내면 당연히 작동하지않음. superPrint(["a","b","c"])
TS에게 이 call signature가 generic을 받는걸 알려주는 법
type SuperPrint = { <TypePlaceholder>(arr: TypePlaceholder[]): void; };
대박 이런 형태 너무새롭다
이렇게하면 이제 ts가 타입을 유추한다.
type SuperPrint = { <TypePlaceholder>(arr: TypePlaceholder[]): void; }; const superPrint: SuperPrint = (arr) => { arr.forEach((i) => console.log(i)); }; superPrint([1, 2, 3, 4]); superPrint([true, false, true]); superPrint(["a", "b", "c"]); superPrint([1, 2, true, false]);
우리 타입스크립트야... 내가 명시도안했는데 타입을 유추한거야?
제가 요즘 좀 개그욕심이있어요 2. 배열의 첫번재 요소를 리턴하는 함수 superPrint1
type SuperPrint1 = { <TypePlaceholder1>(arr: TypePlaceholder1[]): TypePlaceholder1; }; const superPrint1: SuperPrint1 = (arr) => arr[0]; const b = superPrint1([1, 2, 3, 4]); const c = superPrint1([true, false, true]); const d = superPrint1(["a", "b", "c"]); const e = superPrint1([1, 2, true, false]);
이번엔 return이 void가 아닌, 배열 내 요소가 될 때이다.
여기서도 마찬가지로 알려주지 않아도 스스로 유추를한다...
장하다 타입스크립트야..... 728x90'Java Script & Type Script > TIL' 카테고리의 다른 글
React 클로저(closure) 딱 대.. (2) 2024.12.26 3월 26일 TIL : ReactQuery 시작하기 (0) 2023.03.26 3월 21일 TIL : TypeScript-call signature, unknown,void,never (0) 2023.03.23 3월 18일 TIL : TypeScript 시작 (0) 2023.03.21 3월 18일 TIL : context API, props전송없이 state를 공유하는 방법 (0) 2023.03.18