Sub topic 1
What static typing adds to JavaScript
Prerequisites
This chapter assumes you know basic JavaScript syntax (variables, functions, objects, arrays). It also assumes you can run tsc or use an editor that understands TypeScript, and that you know what a data type such as string or number is.
What static typing adds
JavaScript checks types only while the code runs, so a typo like user.nmae fails in production. TypeScript checks types before the code runs. You write optional annotations such as : number, and the compiler reports mismatches. Then it erases the annotations and emits plain JavaScript. Types have no runtime cost and give no runtime guarantee.
The primitive types
| Type | Example value |
|---|---|
| `string` | `"hello"` |
| `number` | `42`, `3.14` |
| `boolean` | `true` |
| `bigint` | `10n` (needs target ES2020 or later) |
| `symbol` | `Symbol("id")` |
Use the lowercase names. String and Number are wrapper object types, and using them is a common mistake.
How TypeScript infers types
If a variable has an initializer, you rarely need an annotation. The compiler infers the type from the value:
let count = 0; // inferred as number
const name = "Ada"; // inferred as the literal type "Ada"
let items = [1, 2, 3]; // inferred as number[]
count = 5; // ok
// count = "five"; // Error: Type 'string' is not assignable to type 'number'.Add annotations where inference has nothing to work from: a variable declared without a value, a function parameter, or a public API whose type you want to lock down.
const, let, and literal widening
A const can never be reassigned, so TypeScript keeps the narrowest type for it: the literal "Ada". A let can change, so the compiler widens its literal type to the primitive, string. This difference matters later, when a function expects a specific literal such as "dev".
Arrays and tuples
An array holds any number of elements of one type, written number[]. A tuple has a fixed length, and each position has its own type:
const entry: [string, number] = ["age", 30];
const ids: readonly number[] = [1, 2, 3];
// ids.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.Exercise
What types does TypeScript infer for let a = "x";, const b = "x";, and let c = [true, 1];?
Show answer
a is string because let widens the literal. b is the literal type "x" because const keeps it. c is (boolean | number)[] because array literals are inferred as arrays, not tuples.