Sub topic 1
Why TypeScript?
TypeScript is JavaScript with a static type system added on top. A static type system checks, before the program runs, whether values are used in ways that match their declared shapes. This chapter explains which problems that solves, which it doesn't, and what you pay for it. Later chapters cover installing and configuring the compiler.
Prerequisites
This chapter assumes you have the following:
- Working knowledge of JavaScript: functions, objects, arrays, and ES modules (
importandexport). - Basic use of a terminal.
- Node.js and npm installed.
- Familiarity with
package.json.
You don't need to know TypeScript syntax yet. The few annotations that appear below are explained where they are used.
The problem: JavaScript fails late
JavaScript is dynamically typed. A variable can hold a string now and a number later, and the engine checks types only at the moment an operation runs. This keeps the language flexible. It also means many mistakes surface late: in a rarely executed branch, in production, or never as an error at all.
Here is a small example in plain JavaScript:
function total(price, quantity) {
return price * quantity;
}
console.log(total(4, 5));
console.log(total("4", 5));
console.log(total("four", 5));The three calls print 20, 20, and NaN. None of them throws an error. JavaScript silently converts the string "4" to a number, and "four" becomes NaN (not a number). The bad value then flows onward into totals, database writes, or rendered pages. By the time someone notices, the cause is far from the symptom.
Three kinds of mistakes are typical:
- Wrong argument types. A function expects a number and receives a string, often from a form field, query string, or environment variable.
- Misspelled or missing properties.
user.nmaeevaluates toundefinedinstead of failing. - Unhandled
undefinedandnull.text.charAt(0)throws aTypeErroronly whentexthappens to be missing.
TypeScript moves these failures from runtime to the editor and the build.
The same code in TypeScript
You describe the types you expect by writing type annotations after names. An annotation is a colon followed by a type, such as name: string.
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet(42));The annotation name: string says the parameter must be a string. The second : string after the parentheses says the function returns a string. The compiler, tsc, rejects the last line:
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.Nothing ran. The editor underlines 42 as you type, and the build fails if the error remains. Plain JavaScript would print Hello, 42! and carry on.
Typos get the same treatment. The compiler also suggests the fix:
interface User {
id: number;
name: string;
}
function label(user: User): string {
return user.nmae;
}This produces error TS2551: Property 'nmae' does not exist on type 'User'. Did you mean 'name'?
What you gain
Earlier feedback
Type errors appear while you edit, not after you deploy. The cost of fixing a bug generally rises the later you find it, and a red underline in the editor is the earliest point available.
Safer refactoring
Rename a field, add a required parameter, or change a return type, and the compiler lists every place that no longer fits. In a large JavaScript codebase you would search for usages and hope you found them all. With types, an empty error list is real evidence that the change is consistent.
Types as documentation that stays accurate
A comment can drift away from the code it describes. A type annotation cannot, because the compiler enforces it. A signature such as (userId: number, options?: FetchOptions) => Promise<User> tells a reader what to pass and what comes back without opening the function body.
Better editor tooling
Autocomplete, hover information, go-to-definition, and rename-symbol all rely on knowing the types. The editor support for JavaScript in many editors is itself powered by the TypeScript language service, so you get some of this benefit even before you adopt TypeScript fully.
Access to modern syntax
The compiler can lower newer JavaScript syntax to older targets, so you can write current code and still support older runtimes. Modern bundlers can do the same job, so this is a convenience more than a reason to choose TypeScript.
How it fits together
TypeScript does not replace JavaScript at runtime. You write .ts files, the compiler checks them, and it emits ordinary .js files. Those .js files are what Node.js or the browser executes.
The key consequence is called type erasure: annotations exist only at compile time and leave no trace in the output. The emitted greet function is the same JavaScript you would have written by hand, minus the annotations. TypeScript therefore adds no runtime cost, and it also provides no runtime protection. The next chapters on static typing and the compilation model go deeper into this.
What TypeScript does not do
The most common errors in using TypeScript come from believing it guarantees more than it does.
It does not validate data at runtime
Types describe what you claim about a value. They are not checked when the program runs. Data that crosses a boundary, such as a network response, a file, or user input, can be anything.
interface User {
id: number;
name: string;
}
const user = JSON.parse('{"id": "7", "name": "Ada"}') as User;
console.log(user.id.toFixed(2));This compiles without error, because JSON.parse returns any and as User is an assertion that tells the compiler to trust you. At runtime user.id is the string "7", so the last line throws TypeError: user.id.toFixed is not a function. To be safe at boundaries, validate the data, with a schema library or hand-written checks, and let the validated result carry the type.
Escape hatches switch checking off
Two features let you opt out of checking:
- The type
anydisables checking for a value. Any operation on it is allowed, and it spreads: values derived from ananyoften becomeanytoo. - A type assertion (
value as Type) overrides what the compiler inferred. If you are wrong, the compiler will not notice.
Both have legitimate uses, such as migrating old code or handling a truly dynamic value. A codebase with many of them gets little protection while still paying the cost of the build step.
A passing build is not a correct program
Types catch a category of mistakes: mismatched shapes, missing properties, unhandled undefined. They do not catch wrong business logic. price * quantity type-checks just as well when the formula should have been price + tax. You still need tests.
Strictness is a setting
The compiler's protection depends on its configuration. With loose settings, the missing-value mistake from the opening section compiles cleanly:
function firstLetter(text: string | undefined): string {
return text.charAt(0);
}With strict mode enabled, tsc reports that text is possibly undefined. A later chapter covers tsconfig.json and strict mode. For now, keep in mind that "we use TypeScript" does not say how much checking is happening.
What it costs
TypeScript is a tradeoff, so weigh the costs:
- A build step. Something has to remove the types before the code runs. That means a compiler or a tool that strips types, plus configuration to maintain.
- Configuration.
tsconfig.jsonhas many options, and some interact in ways that surprise people, especially the module-related ones. - A learning curve. Basic annotations are easy. Generics, conditional types, and narrowing take real study.
- Types for dependencies. A JavaScript library without bundled types needs a separate type package, or you must declare the types yourself.
- Ceremony in small scripts. For a throwaway script of thirty lines, the setup may cost more than it saves.
Deciding whether to adopt it
TypeScript pays off most when several of these hold:
- The codebase will live for months or years.
- More than one person works on it, or you will return to it after a long break.
- You expect to refactor, so a list of what broke is valuable.
- The code has many internal interfaces, such as shared modules, APIs, or components.
It pays off least for short-lived scripts, quick prototypes, or tiny projects where one person holds all the code in their head. Even there, many developers use TypeScript for the editor support.
Adoption can be gradual. TypeScript can compile existing JavaScript files, so teams often migrate one module at a time and tighten the settings over time.
Summary
- JavaScript checks types only when code runs, so many mistakes show up late, or as silent wrong values like
NaN. - TypeScript adds annotations and a compiler that checks them and then emits plain JavaScript with the types erased.
- The benefits are early error detection, safer refactoring, accurate documentation, and better editor tooling.
- The limits are real: no runtime validation, escape hatches such as
anyandas, no check of business logic, and protection that depends on configuration. - The costs are a build step, configuration, a learning curve, and dependency typings. Whether they are worth paying depends on project size, lifespan, and team.
Exercise
A teammate says, "The project is written in TypeScript and builds with no errors, so the JSON response we get from the payments API must have the shape our Payment interface describes." Is the conclusion justified? Explain, and name one way to make it so.
Show answer
No. Types are erased when the code is compiled, so nothing checks the real response at runtime. If the code reads the response with JSON.parse or response.json(), the result is any, and a cast such as as Payment only tells the compiler to trust you. If the API returns a different shape, the build still passes and the failure appears at runtime, for example as a TypeError. To make the claim true, validate the response when it arrives, using a schema validation library or hand-written checks, and give the validated value the Payment type only after it passes.
Exercise
In plain JavaScript, total("four", 5) returns NaN without any error. If you rewrite the function as function total(price: number, quantity: number): number, what happens on that call, and at what point in the workflow do you find out?
Show answer
The compiler reports error TS2345, because the argument of type string is not assignable to the parameter of type number. You find out at compile time, usually in the editor while typing and otherwise when you run tsc, before the program runs at all.