
Type inference
Type inference is used when the type is not provided explicitly. For instance in the following statements:
var x = "hello";
var y = 99;
These don't have explicit type annotations. TypeScript can infer that x is a string and y is a number. As you see, the type can be omitted if the compiler is able to infer it. TypeScript improves the type inference continuously. It tries to guess a best common type when elements of several types are present in an array. The type of the following variable animal, where Sheepdog extends Dog, is Dog[]:
let animal = [new Dog(), new Sheepdog()];
The best common type of the next array is (Dog | Fish)[] because the class Fish doesn't extend to any other class:
class Fish {
kind: string;
}
let animal = [new Dog(), new Sheepdog(), new Fish()];
Type inference is also used for functions. In the next example, the compiler can figure out the types of the function's parameter (string) and the return value (boolean):
let isEmpty: (param: string) => boolean;
isEmpty = function(x) {return x === null || x.length === 0};