Published on

Type Inferences

Authors

Type Inferences

TypeScript is a superset of JavaScript that adds types.

Primitive data types (javascript's built in data types)

  • boolean
  • number
  • null
  • string
  • undefined

if we tey to reassign a variable to a value of different type, TypeScript will surface an error.


Type Shapes

The bulit-in types in JavaScript each have known properties and methods that always exist. All strings for example, are known to have s .length property and .toLowerCase() method

TypeScript's tsc command will let you know if your code tried to access properties and methods that don't exist:

  "My".toLowercase();
   // Property 'toLowercase' does not exist on type '"MY"'.
   // Did you mean 'toLowerCase'? 

Any

Varaibles of type any can be assigned to any value and TypeScript won't give an error if they're reassigned to a differnet type later on

There are some places where TypeScript will not try to infer what type something is—generally when a variable is declared without being assigned an initial value. In situations where it isn’t able to infer a type, TypeScript will consider a variable to be of type any

  // the following code is correct
  let onOrOff
  onOrOff = 1;
  onOrOff = false;

Variable Type Annotations

we can declare varaible without assign it an initial value, but we can declare what type it will be contain in the future by useing : after varaible name and set data type

let mustBeAString : string;
mustBeAString = 'CatDog'; // correct

mustBeAString = 1337;
// Error: Type 'number' is not assignable to type 'string'