Typescript Type Inference

Basic

분명하게 type annotation을 기술하지 않으면 type 추론(inference)이 사용됩니다.

1
x = 3;

x 변수의 type은 number로 추론됩니다. 이러한 종류의 추론은 변수와 멤버를 초기화하고, parameter 기본값을 설정하고, 함수 return type을 결정할 때 발생합니다.

Contextual Type

type 추론는 TypeScript의 “다른 방향”에서도 작동합니다. 이를 “문맥적 타이핑(contextual typing)”이라고합니다. contextual typing은 표현식 type이 위치에 의해 암시 될 때 발생합니다.

1
2
3
window.onmousedown = function(mouseEvent) {
console.log(mouseEvent.buton); // 에러
};

Window.onmousedown 함수 type으로 할당문의 오른쪽에있는 함수의 type과 mouseEvent parameter의 type을 추론할 수 있습니다.

명확하게 type을 기술하면 contextual type은 무시됩니다.

1
2
3
window.onmousedown = function(mouseEvent: any) {
console.log(mouseEvent.buton);
};

contextual typing은 대부분의 경우에 적용됩니다. 일반적으로 함수 호출에 대한 argument, assignment의 오른쪽, type assertion, object와 array literal의 멤버, return 문에 적용됩니다.

Share