Comp 110 Type Inference

Type Inference with Variables

With type inference, if we initialize a variable, TypeScript can infer its type without us having to explicitly write out the type. Since we want to use type inference when we declare and initialize a variable all on one line, the type of the initial value we give the variable will be the type associated with the variable from then on. So, if we decide later that we want to assign a new value to the variable, we've got to make sure whatever new value we choose has the same type as our initial value did. Let's look at an example:

let myFavColor = "red";
// ^^ TypeScript infers that the type of myFavColor is string
 
// now to reassign myFavColor:
myFavColor = 47; // ERROR--types don't match
 
// TypeScript infers myFavColor is a string, so we must give it a string
myFavColor = "blue"; // this works since "blue" is a string!

If we don't want to initialize the variable in the same line where we declare it, we should specify a type when we declare the variable:

let myFavNumber: number;
myFavNumber = 110;

Type Inference with Functions

Type inference works with functions, too - we've been using type inference for functions this whole semester! Just as we have the option to use type inference with variables (but we don't have to), even though we've been using type inference for functions we can still explicitly type them if we want:

let isLength3 = (s: string): boolean => {
      return s.length === 3;
};
// The above uses type inference
// The version below has an explicit type
let isLength3: Predicate<string> = (s: string): boolean => {
      return s.length === 3;
};

The isLength3 function works and the returns the boolean value that results from the s.length === 3 expression.