[1,2,3].forEach((item) => console.log(item));
item이 number로 자동으로 추론이 된다
['1','2','3'].forEach((item) => console.log(item));
이번에도 string으로 추론이 된다
boolean으로 마찬가지로 추론된다
lib.es5.d.ts
파일의 forEach를 분석하자
interface Array<T> {
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
}
forEach는 Generic T를 통해서 주입되는 Array의 타입을 그대로 value: T로 추론한다.
그렇기 때문에 자동 추론이 가능한 것이다.
function add<T>(x: T, y: T) {return x}
const a = add(1,2)
타입을 숫자값으로 추론하고 있다
매개변수에 서로 다른 타입의 값을 넣어보자. 어떤 문제가 발생할까?
const aa = add(1,'2')
x, y파라미터 모두 동일한 T타입으로 선언되었지만, 서로 다른 타입의 매개변수로 적용되어 있어 위와같은 오류가 난다
이를 해결하기 위해서는 새로운 제네릭 변수 U
를 추가하면 된다.
function add<T, U> (x: T, y: U) { return x }
interface Array<T> {
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
map<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[];
}
const str = [1,2,3].map(item => item.toString())
const str1 = [1,2,3].map(item => item)
const str2 = [1,2,'3'].map(item => item)
str: string[]
추론이 되는 이유는 map의 callbackfn
의 리턴타입이 U
이고, map전체의 리턴값의 타입또한 U[]
이기 때문에 item.toString()의 반환값의 타입이 추론될 수 있다
우리가 사용하는 내장 메소드들의 (forEach, map, every 등등..) 다양한 타입을 lib.es5.d.ts
파일에서 뜯어볼 수 있다.
뜯어보면서 어떻게 타입을 선언했는지 확인하면서 부지런히 학습해보자