let x = 3;
x의 타입은 number로 유추된다. 이러한 종류의 추론은 변수와 멤버를 초기화하고, 매개변수 기본값을 설정하고, 함수 반환 타입을 결정할 때 발생합니다.
대부분의 경우 타입유추는 간단하지만 그 미묘한 차이를 알아보자!
let x = [0, 1, null];
best common type 알고리즘은 각각의 후보들(number, null)을 고려한 뒤에, 모든 후보군을 포괄할 수 있는 타입을 선택합니다.
let zoo = [new Rhino(), new Elephant(), new Snake()];
이상적으로 zoo가 Animal[]로 추론되기를 원하지만, 배열에 Animal 타입이 후보군에 없음으로, 타입의 추론이 불가능합니다. 이걸 고치기 위해서, 어떤 타입도 다른 타입의 super 타입이 아닐 경우 명시적으로 super 타입을 적어주어야 합니다.
let zoo:Animal[] = [new Rhino(), new Elephant(), new Snake()];
만약 best common type이 발견되지 않았을 경우, 추론의 결론은 union 배열타입(Rhino | Elephant | Snake)이 됩니다.
타입스크립트의 몇가지 경우에서 타입 추정은 또한 “다른 지시자” 작동하기도 합니다. 이건 “contextual typing”이라고 불립니다. Contextual typing은 타입이 타입이 필요한 장소에서 암시가 되었을 때 발생합니다.
window.onmousedown = function(mouseEvent) { console.log(mouseEvent.button); //<- OK console.log(mouseEvent.kangaroo); //<- Error! }; // window.onmousedown 함수의 매개변수를 유추하여 mouseEvent의 타입을 유추할 수 있다
window.onscroll = function(uiEvent) { console.log(uiEvent.button); //<- Error! } // window.onscroll 함수에 대응되는 함수이므로 uiEvent를 유추합니다.(앞의 예는 mouseEvent을 유추하였지만)
// 이 함수는 문맥적 타입 위치에 있지 않으므로, 함수의 매개변수는 암묵적 타입은 ''any''이다. --noImplicitAny옵션을 사용하지 않는다면, 발생되는 error는 없다. const handler = function(uiEvent) { console.log(uiEvent.button); //<- OK }
// 명시적으로 타입정보를 준다면... window.onscroll = function(uiEvent: any) { // override function console.log(uiEvent.button); //<- Now, no error is given };
function createZoo(): Animal[] { return [new Rhino(), new Elephant(), new Snake()]; }
Animal, Rhino, Elephant, 그리고 Snake라는 4개의 타입 후보군이 있습니다. 이들 중에서 Animal은 best common type 알고리즘에 의해 선택받습니다.