Type Inference
One common misconception about TypeScript's types is that code needs to explicitly describe types at every possible opportunity. Fortunately this is not the case. TypeScript has a rich type inference system that will "fill in the blanks" for the programmer. Consider the following:
type-inference-finds-error.ts
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 still able 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
In this example the context is not obvious since the interfaces have been defined explicitly. In a browser environment with a real window
object, this would be a handy feature, especially the type completion of the Event
object.
Last updated