
- 특정 함수 타입을 다른 함수 타입으로 취급해도 괜찮은지 판단하는 것
💡 함수 타입 호환성을 판단할 때 필요한 체크리스트
1️⃣ 반환값의 타입이 호환되는가
2️⃣ 매개변수의 타입이 호환되는가
type A = () => number;
type B = () => 10;
let a: A = () => 10; // number 타입
let b: B = () => 10; // number 리터럴 타입
a = b;
b = a;
a는 number 타입이며, b는 number 리터럴 타입이다.b = a는 number 타입을 number 리터럴 타입으로 취급 하겠다는 뜻type C = (value: number) => void;
type D = (value: 10) => void;
let c: C = (value) => {};
let d: D = (value) => {};
c = d;
d = c;
이번에는 C가 number타입이고, D가 number리터럴 타입이다.
이 때 c = d 에서 업캐스팅인데 오류가 발생하고, 아래 d = c는 다운캐스팅인데도 오류가 발생하지 않는다.
다음 예시
type Animal = {
name: string;
};
type Dog = {
name: string;
color: string;
};
let animalFunc = (animal: Animal) => {
console.log(animal.name);
};
let dogFunc = (dog: Dog) => {
console.log(dog.name);
console.log(dog.color);
};
animalFunc = dogFunc;
dogFunc = animalFunc;
let testFunc = (animal: Animal) => {
console.log(animal.name);
console.log(animal.color);
};
let testFunc2 = (dog: Dog) => {
console.log(dog.name);
console.log(dog.color);
};
Animal 타입이 Dog 타입의 슈퍼타입이다.animalFunc = dogFunc은 오류를 발생한다.Animal 자리에 Dog 전용 함수를 넣으면 Animal 호출을 처리 못해서 위험type Func1 = (a: number, b: number) => void;
type Func2 = (a: number) => void;
let func1: Func1 = (a, b) => {};
let func2: Func2 = (a) => {};
func1 = func2;
func2 = func1;
func2 = func1은 오류를 발생func1를 func2로 취급하겠다"라는 뜻인데, func2는 매개변수가 하나이고, func1은 두개이기 때문한 입 크기로 잘라먹는 타입스크립트
https://www.inflearn.com/course/한입-크기-타입스크립트/dashboard