Sub topic 1
What Static Typing Adds to JavaScript
This chapter explains what TypeScript's static type system adds on top of JavaScript, what it leaves alone, and where its guarantees stop. Later chapters cover each basic type in detail. Here you build the working model that those chapters rely on.
Prerequisites
This chapter assumes you can:
- Read and write basic JavaScript: variables, functions, objects, and arrays.
- Run TypeScript with
tscor see errors in a TypeScript-aware editor such as VS Code. - Recognize the idea of a data type, such as a string or a number.
You do not need to know any TypeScript syntax yet. The examples introduce the small amount you need.
The problem: JavaScript checks types too late
JavaScript is dynamically typed. Every value has a type at runtime, but variables and parameters have no declared type. The engine checks nothing until the code actually runs, and many wrong operations do not fail. They produce odd results instead.
function total(price, quantity) {
return price * quantity;
}
console.log(total(5, 3)); // 15
console.log(total("5", 3)); // 15, the string is silently coerced
console.log(total("five", 3)); // NaN, no error is thrownThe third call is a bug, but JavaScript reports nothing. The NaN flows onward into whatever code uses the result. You find the problem far from its cause, often in production.
Static typing moves this check earlier. A static type system analyzes your source code without running it and reports type errors before the program starts.
What a type is
A type is a set of values together with the operations that are valid on them. The type number covers values like 1, -4.5, and NaN, and allows arithmetic and methods such as toFixed. The type string allows toUpperCase but not toFixed.
A type annotation is a note you write in the code to state the type of a variable, parameter, or return value. In TypeScript the annotation follows a colon.
function total(price: number, quantity: number): number {
return price * quantity;
}
total(5, 3); // ok
// total("five", 3); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.The compiler now rejects the bad call at the moment you write it. In an editor, a red underline appears before you save the file.
TypeScript is a superset of JavaScript
TypeScript is a superset of JavaScript. Every valid JavaScript program is also syntactically valid TypeScript, and TypeScript adds type syntax on top. The compiler, tsc, does two separate jobs:
- It checks types and reports errors.
- It emits plain JavaScript with the type syntax removed.
This is called type erasure. Types exist only at compile time. The emitted JavaScript contains no trace of : number and no runtime type check.
Type erasure has three consequences that matter in practice:
- Type errors and emitted code are independent. By default
tscstill writes JavaScript when it finds type errors, unless you set thenoEmitOnErroroption. - Types cannot be inspected at runtime. You cannot write
if (x instanceof number)or ask whether a value "is aPoint" using the type name. - The type system gives no protection against data that arrives from outside your code, such as JSON from a network request.
Static versus dynamic checking
The words "static" and "dynamic" describe when a check happens.
| Property | Dynamic typing (JavaScript) | Static typing (TypeScript) |
|---|---|---|
| When types are checked | At runtime, when the line executes | At compile time, before execution |
| Where types live | On values only | On values, variables, parameters, and returns |
| Wrong call to a function | Runs, may give wrong output | Compile error |
| Cost | None | Annotations, a compile step |
| Runtime overhead | None | None, types are erased |
Both systems can coexist. TypeScript does not replace JavaScript's runtime behavior. It adds a second layer of checking that runs earlier.
What the compiler catches
Static typing finds several common categories of mistakes without running any code.
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: "Ada" };
// user.nmae; // Error: Property 'nmae' does not exist on type 'User'. Did you mean 'name'?
// user.id.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'number'.
// const u2: User = { id: 2 }; // Error: Property 'name' is missing in type '{ id: number; }'.The three errors are a misspelled property, a method called on the wrong type, and a missing required field. Each would be a runtime undefined or a TypeError in plain JavaScript.
Other benefits come from the same analysis:
- Editor support. Because the compiler knows the type of
user, the editor can autocompleteuser.withidandname, show signatures, and rename a property across files safely. - Safer refactoring. If you change a function's parameter type, every call site that no longer fits becomes an error.
- Documentation that stays accurate. An annotation is checked against the code, so unlike a comment it cannot silently go out of date.
Annotations are optional: inference
You do not have to annotate everything. When a variable is initialized, TypeScript infers its 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'.Inference means you get most of the safety of static typing without writing types everywhere. A common working rule is to annotate function parameters and public boundaries, and let inference handle local variables. Later chapters cover inference rules and when an explicit annotation is worth adding.
The type system's limits
Static typing is a tool for catching a specific class of errors. It does not make a program correct.
- Types describe shape, not correctness.
total(-5, 3)is a valid call with a nonsensical result. The typenumberallows negative values. - External data is not checked.
JSON.parsereturns a value the compiler cannot verify. If you claim it has a type, the compiler believes you. - The type system can be bypassed. Escape hatches such as
anyand type assertions tell the compiler to stop checking. They are useful, and they are the main source of types that do not match reality. - It is structural, not nominal. TypeScript compares the shape of types, not their declared names. Two types with the same properties are interchangeable.
The JSON.parse case shows the gap between compile time and runtime.
interface User {
id: number;
name: string;
}
const user = JSON.parse('{"id": "oops"}') as User;
// The compiler accepts this, but at runtime user.id is a string and user.name is undefined.
console.log(user.id);The compiler trusts the as User assertion. The wrong data passes through, and the failure appears later. Because types are erased, only a runtime check of the data can catch this, which is why a later chapter introduces unknown and narrowing.
Strictness settings
How much TypeScript checks depends on the compiler options in tsconfig.json. The most important one is strict, which turns on a family of checks including strictNullChecks and noImplicitAny.
{
"compilerOptions": {
"target": "ES2022",
"strict": true
}
}Without strict, the compiler allows more unsafe code. For example, a parameter with no annotation silently becomes the type any, which disables checking for it. With strict, the same parameter is an error.
// With "strict": true
// function double(n) { return n * 2; } // Error: Parameter 'n' implicitly has an 'any' type.
function double(n: number) {
return n * 2;
}This tutorial assumes strict is on. Examples that depend on it, such as the handling of null and undefined, behave differently without it.
Common errors when starting out
- Expecting runtime checks. Annotating a parameter as
numberdoes not stop a string from arriving at runtime if the data came from outside TypeScript code. - Treating errors as optional. Since
tsccan emit JavaScript despite errors, a build can ship broken code. Run the type check as a required step in your build or continuous integration. - Over-annotating. Writing
const name: string = "Ada"adds noise and, for aconst, widens the type from the literal"Ada"tostring. - Reaching for
anyto silence an error. This hides the problem instead of fixing it. Prefer fixing the type, or useunknownand narrow it.
Summary of the model
Keep these points as the base for the rest of the tutorial:
- TypeScript adds a compile-time layer of checking to JavaScript.
- Types attach to variables, parameters, and return values, not just to runtime values.
- The compiler infers many types, so annotations are needed mainly at boundaries.
- Types are erased, so they cost nothing at runtime and protect nothing at runtime.
- Escape hatches and external data are where the type system and reality can disagree.
Exercise
Look at this code compiled with "strict": true. Will tsc report an error, and what will the emitted JavaScript contain for the function signature? function greet(name: string): string { return "Hello, " + name; } greet(42);
Show answer
Yes. tsc reports an error on greet(42) because the argument of type number is not assignable to the parameter of type string. The emitted JavaScript still contains the function as function greet(name) { return "Hello, " + name; }, because type annotations are erased. Unless noEmitOnError is set, the file is emitted despite the error, and at runtime greet(42) would return "Hello, 42".
Exercise
A teammate writes const order = JSON.parse(text) as Order; and says the data is now guaranteed to match Order. What is wrong with this claim, and what should the code do instead?
Show answer
The assertion only tells the compiler to trust the type. Types are erased at runtime, so nothing checks that the parsed data has the fields of Order. Instead, parse into unknown and narrow it with runtime checks (or a validation library) before using it as Order.