쇤네 요즘 타입스크립트를 정복하고자하여 노X드코더 챌린지 진행ing
🥔 : 오늘의 문제는 이러하다 배열만드는거 EASY하지 후후
🥔 : 문제는 타입스크립트 옷을 입혀가지고 뽀송뽀송하게 코드를 만들어야 한다는 것
하지만 걱정마라 내 두뇌는 아직 쓸만하니까
앞에서 타입작성 뒤에서 타입작성...
🖥 : 동작그만 밑장빼기냐 ?
🥔 뭐야 ?
🖥 : 넌 나한테 arr.unshift(itme)
을 줬지 근데 이거 이거 ... 뭐 하나 빠자먹은거 아냐 ?
🥔 : 시나리오 쓰고 있네 미X새X가..!
🖥 : 니가 return
을 안줬다는것에 내 전부와 팔모가지 건다. 넌 무엇을 걸래?
🥔 : .....(뭐야 IMMA)
🖥 : 쫄리면 DZ시던지
🦭 말하는 감자는 오늘도 return
을 주지 않는 실수를 하는군요
🦭 암튼 행복하게 과제를 마쳤답니다
🤔 그렇다면 그냥 any를 넣는 것과 Generic의 차이는 무엇일까?
type SuperPrint = {
(arr: any[]): any
}
const superPrint: SuperPrint = (arr) => arr[0]
let a = superPrint([1, "b", true]);
// pass
a.toUpperCase();
any를 사용하면 위와 같은 경우에도 에러가 발생하지 않는다
type SuperPrint = {
(arr: T[]): T
}
const superPrint: SuperPrint = (arr) => arr[0]
let a = superPrint([1, "b", true]);
// error
a.toUpperCase();
Generic의 경우 에러가 발생해 보호받을 수 있다
✔️ Call Signature를 concrete type으로 하나씩 추가하는 형태이기 때문!
type SuperPrint = {
(arr: T[], x: M): T
}
const superPrint: SuperPrint = (arr, x) => arr[0]
let a = superPrint([1, "b", true], "hi");
위와 같이 복수의 Generic을 선언해 사용할 수 있다
//적용방법
type = {a : T} : T
type Add = {
(a: number, b: number): number,
(a: number, b: string): number
}
const add: Add = (a, b) => {
if (typeof b === "string") return a;
return a + b;
}
매개변수의 데이터 타입이 다른 경우 예외 처리
type Add2 = {
(a: number, b: number): number,
(a: number, b: number, c: number): number
}
const add2: Add2 = (a, b, c?: number) => {
if (c) return a + b + c;
return a + b;
}
매개변수의 수가 다른 경우 예외 처리
위와 같은 함수는 거의 없지만 외부 라이브러리에서 활용될 수 있다
router.push("/home");
router.push({
path: "/home",
state: 1
});
예를 들어, Next.js의 라우터 push가 대충 두 가지 방법으로 페이지를 이동한다고 할 때,
type Config = {
path: string,
state: number
}
type Push = {
(config: Config): void,
(config: string): void
}
const push: Push = (config) => {
if (typeof config === "string") console.log(config);
else console.log(config.path);
}
패키지나 라이브러리는 위와 같이 두 가지 경우의 Overloading으로 디자인되어 있을 것이다
화살표 함수에 속에 return
을 잊지말자
타입스크립트 뭔가 코드가 너저분 해지는 것 같은데
배우면 배울수록 JS공부도 되고
내가 똑똑해지는 기분이 들어서 좋다 !