TypeScript infers types of variables when there is no explicit type information available.
TypeScript infers types in following cases:
- Variables are initialized
- Default values are set for function parameters
- Return types of functions are determined
Example of type inference:
var name = "Joe Smith"; var age = 33; a = b; // Compiler Error: Type 'number' is not assignable to type 'string'
TypeScript shows an error because TypeScript auto inferred the type of variable
name as string and variable
age as number.
Type inference in objects
TypeScript looks for the most common type of all the elements in the object to infer the type. Consider the following example:
var list = [ 100, 500, 600, 200 ]; // TypeScript infers the type as :number
Now consider another example:
var list = [ 100, 500, 600, 200, "CA100"]; // TypeScript infers the type as (string | number). Known as union type