TypeScript
  • Introduction
  • Introduction
    • What is TypeScript?
    • Why TypeScript?
    • Setup
  • Beginner
    • Basic types
      • Primitive types
      • Arrays and tuples
      • Enums
      • Any type
    • Objects
    • Type aliases
    • Interfaces
    • Functions
      • Function signatures
      • Void type
      • Functions as types
    • Union types
    • Type guards
    • Intersection types
    • Nullable types
    • Inference
  • Resources
    • Resources
Powered by GitBook
On this page
  1. Beginner

Inference

PreviousNullable typesNextResources

Last updated 6 years ago

Just as we normally declare and define variables in the same statement (e.g., let name = 'Jane';), it's simpler to rely on the TypeScript transpiler to infer the variable's type from its initial assignment. In our example, name is inferred to be of type string because a string was assigned to it when the variable was delcared.

// Unnecessary
const vehicle: string = 'Ford Taurus';

// Preferred
const vehicle = 'Ford Taurus';

Likewise, when defining an object, you're better off leaving it to the transpiler to infer the types of its individual properties. (Though, depending on your requirements, it might make sense to use a or .)

// Unnecessary
const animal: {
  name: string,
  species: string,
  age: number,
  alive: boolean,
} = {
  name: 'Capybara',
  species: 'H. hydrochaeris',
  age: 2,
  alive: true,
};

// Better
const animal = {
  name: 'Capybara',
  species: 'H. hydrochaeris',
  age: 2,
  alive: true,
}; // type inferred: `{name: string, species: string, age: number, alive: boolean}`

The inferred type of a newly-defined array will be :

const foo = [1, 2, 3]; // type inferred: `number[]`
foo[0] = '1'; // Error: cannot assign `string` to a `number`

const bar = [1, 2, 'Capybara', false] // type inferred: `(string | number | boolean)[]`

and when destructuring:

const animal = {
  name: 'Capybara',
  species: 'H. hydrochaeris',
  age: 2,
  alive: true,
};

let {species} = animal;
species = 600; // Error: type '600' is not assignable to type 'string'
species = 600 as number; // Error: type 'number' is not assignable to type 'string'

noImplicitAny

There is a compiler flag noImplicitAny where the compiler will actually raise an error if it cannot infer the type of a variable (and therefore can only have it as an implicit any type). You can then

  • either say that yes I want it to be an any by explicitly adding an : any type annotation

  • help the compiler out by adding a few more correct annotations

type alias
interface