Static versus Dynamic Typing

Learn to judge whether a statically typed or dynamically typed language is better suited to an application.

At the most abstract level, there are two different strategies for dealing with type information in a programing language. These strategies are called static typing and dynamic typing.

Statically typed languages

A language with static types requires that each variable be assigned a type when it is first declared. The language expects to know what the type of a value is and uses that information to constrain at compile time what values can be assigned to that variable.

Different static languages have different requirements for how types are assigned. Some languages, like Java, require the type of every variable to be explicitly stated when the variable is declared. Other languages, like TypeScript, allow for type inference. In TypeScript, if you assign a variable with a typical JavaScript assignment like this:

let x = "hello"

TypeScript infers from the assignment that x is meant to be a string, and does not require further information; you do not have to explicitly declare that x is a string. Later, if we try to say x = 3, the TypeScript compiler will flag this as an error because 3 is not a string.

Test that out in the following TypeScript executable. Note that it will throw an error when the last line is uncommented!

Get hands-on with 1200+ tech skills courses.