Skip to content

Latest commit

 

History

History
82 lines (72 loc) · 3.31 KB

type-inference.md

File metadata and controls

82 lines (72 loc) · 3.31 KB

Type Inference

Type inference is where the compiler can work out the type of a variable, generic parameter, and/or return type for you.

For example:

// the compiler can tell that `input` is a string
// without us having to explicitly say so
const input = "hello world!";

When it works, type inference speeds up the process of writing code, because we don't have to take the time to explicitly say what type something is.

We say "when it works", because the Typescript compiler is written to be fast first, and complete second. The type inference algorithm will bail if it thinks it'll take too much time to work. That said, the compiler developers do keep adding more and more type inference support.

In theory, it can go wrong as well :)

The main problem with type inference is that relying on it is a form of happy path development.

  • If you're not adding types to your code, you might not spot where you've written code to call the wrong function or method.
  • The compiler can't do that for you, because it doesn't know which types you meant to use.

You're effectively using the compiler on auto-pilot, and hoping for the best.