Sub topic 1
What Static Typing Adds to JavaScript
Prerequisites
This chapter assumes you know basic JavaScript syntax: variables, functions, objects, and arrays. You should be able to compile a file with tsc or open a project in a TypeScript-aware editor. You should also understand what a data type such as string or number means.
The problem static typing solves
JavaScript checks types while the program runs. A variable can hold a number on one line and a string on the next. A mistake such as calling a method that does not exist only shows up when that line executes, which may be in production.
TypeScript adds a static type system. Static typing means the types are checked before the program runs, during compilation. The type information is removed from the output, so the emitted JavaScript behaves like the code you wrote.
Annotations and inference
A type annotation is a label you write after a name, such as : number. TypeScript also infers types when you leave annotations out. The compiler reads the value you assign and records its type.
function add(a: number, b: number) {
return a + b;
}
const total = add(2, 3); // total is inferred as number
console.log(total);
// add("2", 3); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.The parameters need annotations because the compiler cannot know what callers will pass. The return type is inferred from a + b.
> Note: The annotations disappear when tsc emits JavaScript. They affect only the compile-time check.
Use this diagram to see the compile step:
When to annotate
Inference works well for local variables with obvious values. Add annotations at boundaries: function parameters, exported functions, and object shapes that other code depends on. Annotations there document intent and stop a bad change from spreading.
Exercise
Given let flag = true;, what type does TypeScript infer for flag, and why does flag = "yes"; fail?
Show answer
TypeScript infers boolean from the initial value. Assigning a string breaks that inferred type, so the compiler reports an error before the code runs.