liveBook · Manning

Dynamic typing

As explained in Essential TypeScript 5, Third Edition

Dynamic typing is a language system in which values carry types at runtime and a variable can refer to values of different types over time.

Dynamic typing lets values carry their types at runtime, so one variable can refer to a string, number, or boolean at different points. JavaScript infers each type from the assigned value. section 3.3.1 section 7.2

Expect these behaviors when working with dynamically typed JavaScript:

  • Inspect a value with typeof; assigning a new value can change the reported type. section 3.3.1 section 7.2
  • Leave a variable unassigned and its value and type are undefined until a value is assigned. section 7.2
  • Rely on JavaScript coercion carefully: loose equality can equate a number and string, while addition can concatenate them. section 3.3.1
  • Remember that typeof null returns object, a long-standing JavaScript behavior. section 3.3.1

A flexible parameter can hide an incorrect assumption

function calculateTax(amount) { return amount * 1.2; } console.log(calculateTax(12)); // 14.399999999999999 console.log(calculateTax("Hello")); // NaN console.log(calculateTax(true)); // 1.2 The function accepts number, string, and boolean arguments. JavaScript processes each call, but only the numeric result matches the function's intended calculation: the string produces NaN, while true is coerced to 1. section 7.2

Listing 7.8 Displaying the variable type in the index.ts file in the src folder
let myVar;
console.log(`${myVar} = ${typeof myVar}`);
myVar = 12;
console.log(`${myVar} = ${typeof myVar}`);
myVar = "Hello";
console.log(`${myVar} = ${typeof myVar}`);
myVar = true;
console.log(`${myVar} = ${typeof myVar}`);

Trace one variable from undefined to number, string, and boolean values, with typeof output after each assignment. section 7.2

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Demonstrates reassignment, typeof inspection, built-in types, and coercion consequences, but does not develop a formal type system.
Examples
Uses reassigned variables, price comparisons, typeof output, and a calculateTax function called with three value types.
What it assumes
Assumes basic JavaScript variables and functions while teaching runtime inference and JavaScript's built-in types.
What you can do after
Diagnose unexpected values by inspecting runtime types and recognizing coercion-related results such as NaN.
How it connects
Connects runtime types with typeof, type coercion, equality, function parameters, and static types.

Also explained in

Compare how 6 books explain dynamic typing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.