Type Inference

One common misconception about TypeScript's types is that code needs to explicitly describe types at every possible opportunity. Fortunately this isnot the case. TypeScript has a rich type inference system that will "fill inthe blanks" for the programmer. Consider the following:

type-inference-finds-error.ts

  1. let numbers = [2, 3, 5, 7, 11];
  2. numbers = ['this will generate a type error'];
  1. tsc ./type-inference-finds-error.ts
  2. type-inference-finds-error.ts(2,1): error TS2322: Type 'string[]' is not assignable to type 'number[]'.
  3. Type 'string' is not assignable to type 'number'.

The code contains no extra type information. In fact, it's valid ES6.If var had been used, it would be valid ES5. Yet TypeScript is stillable to determine type information.

Type inference can also work through context, which is handy with callbacks. Consider the following:

type-inference-finds-error-2.ts

  1. interface FakeEvent {
  2. type: string;
  3. }
  4. interface FakeEventHandler {
  5. (e: FakeEvent): void;
  6. }
  7. class FakeWindow {
  8. onMouseDown: FakeEventHandler
  9. }
  10. const fakeWindow = new FakeWindow();
  11. fakeWindow.onMouseDown = (a: number) => {
  12. // this will fail
  13. };
  1. tsc ./type-inference-finds-error-2.ts
  2. type-inference-finds-error-2.ts(14,1): error TS2322: Type '(a: number) => void' is not assignable to type 'FakeEventHandler'.
  3. Types of parameters 'a' and 'e' are incompatible.
  4. Type 'number' is not assignable to type 'FakeEvent'.
  5. Property 'type' is missing in type 'Number'.

In this example the context is not obvious since the interfaces have beendefined explicitly. In a browser environment with a real window object, thiswould be a handy feature, especially the type completion of the Eventobject.

原文: https://angular-2-training-book.rangle.io/handout/features/type_inference.html