********************************
< 타입이 정해지지 않은 상태에서 if 로 제약을 걸어서 오류를 없애는 건에 대하여 >
예를 들어서, 다음 같은 경우에는 if 가 필요하겠지
——
type Add2 = {
(a:number, b:number) : number
(a:number, b:string) : number
}
const add2 : Add2 = (a, b) => {
if (typeof b === "string") {
return a
}
return a + b;
}
——
=> 왜? 매개변수의 타입에 따라서 함수 안에서 구현될 로직이 달라질 테니까.
반대로, 다음 같은 경우에는 if 가 없어도 오류는 발생하지 않아.
——
type SuperPrint = {
(arr:number[]) : void
(arr:boolean[]) : void
}
const superPrint : SuperPrint = (arr) => {
arr.forEach(console.log)
}
——
=> 왜? 매개변수가 타입 뭐든 간에 함수 내부에서 동작하는 forEach 를 가동시키는 데에는 문제가 없을 테고,
애당초 용도적으로 봤을 때도 타입이 뭐든 간에 함수가 맡은 기능은 같으니까.
즉, if 가 필요한 것은
——
let abc : unknown;
let b = abc + 1
if (typeof abc === "number") {
let bb = abc + 1
}
if (typeof abc === "string") {
let eee = abc.toUpperCase();
}
——
이나
——
type Add2 = {
(a:number, b:number) : number
(a:number, b:string) : number
}
const add2 : Add2 = (a, b) => {
if (typeof b === "string") {
return a
}
return a + b;
}
——
혹은
——
type Add3 = {
(a:number, b:number) : number,
(a:number, b:number, c:number) : number
}
const add3 : Add3 = (a, b, c?:number) => {
if (c) return a + b + c;
return a + b;
}
——
처럼 매개변수의 타입에 따라 함수가 기동하는 로직이 달라져서 분기를 시키지 않으면 오류가 발생하는 경우인 거야.
반대로
——
type SuperPrint = {
(arr:number[]) : void
(arr:boolean[]) : void
}
const superPrint : SuperPrint = (arr) => {
arr.forEach(console.log)
}
——
처럼 딱히 타입으로 명시해서 제한한 조건 중 어느 조건이더라도 상관없이 내부 로직이 돌아가는 경우라면,
If 가 없어도 오류 없이 그저 인자를 출력해줄 뿐인거지.
끝!
타입스크립트에 대해 더 알고 싶다면, TypeScript HandBook 이라는 걸 읽어봐!
'내일배움캠프_개발일지 > TypeScript 연습' 카테고리의 다른 글
TypeScript 연습 <1> -20- (0) | 2023.02.13 |
---|---|
TypeScript 연습 <1> -19- (0) | 2023.02.13 |
TypeScript 연습 <1> -18- (0) | 2023.02.10 |
TypeScript 연습 <1> -17- (0) | 2023.02.09 |
TypeScript 연습 <1> -16- (0) | 2023.02.08 |