Type Inference
Let's consider the following code:
const myFunction = (name: string): string => `Hello ${name}!`; const numbers = [1, 3, 2]; const filtered = numbers.filter((val) => val < 3); console.log(filtered);
The output is as follows:
[1, 2]
Notice that in the preceding code, we aren't specifying a type for the numbers
constant. But wait, isn't this a book on TypeScript? Yes, and now we come to one of the best features of TypeScript: type inference. TypeScript has the ability to assign types to variables when we omit them. When we declare const numbers = [1, 2, 3];
, TypeScript will intuitively understand that we are declaring an array of numbers. If we wanted to, we could write const numbers: number[] = [1, 2, 3];
, but TypeScript will see these declarations as equal.
The preceding code is 100% valid ES6 JavaScript. This is great because any JavaScript developer will be able to read and understand it, even if they have no experience with TypeScript...