Expert · TypeScript basics · topic 42 of 61 · 20 min
Why TypeScript
Explanation
The problem TypeScript solves
JavaScript only finds many mistakes when the code runs, sometimes in front of a customer: calling a function with arguments in the wrong order, misspelling a property (user.nmae), or forgetting that a value can be null. In a 200,000-line codebase with 30 developers, these bugs are expensive. TypeScript (made by Microsoft, first released in 2012) adds a type system that checks the code while you write it.
function totalPrice(price: number, qty: number): number {
return price * qty;
}
totalPrice(499, 2); // OK
totalPrice('499', 2); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
const u = { name: 'Asha' };
u.nmae; // Error: Property 'nmae' does not exist. Did you mean 'name'?How it works
- You write .ts files (or .tsx for React) with type annotations like : number.
- The TypeScript compiler, tsc, checks the types and reports errors.
- It outputs plain .js files with the types removed (this is called type erasure). Browsers and Node run that JavaScript.
Because types are erased, they do NOT exist at run time. TypeScript cannot check data that arrives while the program runs, such as JSON from an API. You still need run-time checks at those boundaries.
Getting started
npm install --save-dev typescript
npx tsc --init # creates tsconfig.json
npx tsc # type-check and compile
npx tsc --noEmit # only type-check (common in projects that use a bundler)tsconfig.json holds the settings. The most important one is "strict": true, which turns on the full set of checks, including strictNullChecks (null and undefined must be handled). Always start new projects with strict on; turning it on later is painful.
Type inference: you do not annotate everything
TypeScript works out (infers) types from values. let count = 0 is already a number; writing let count: number = 0 adds nothing. Annotate function parameters, and the return type of important functions; let inference handle most local variables.
let city = 'Pune'; // inferred: string
city = 42; // Error: Type 'number' is not assignable to type 'string'.
const prices = [10, 20]; // inferred: number[]
const total = prices.reduce((a, b) => a + b, 0); // inferred: numberNeed help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Why TypeScript · 1/6
In this module you will learn TypeScript, which is JavaScript with types.
Prefer a video by a teacher? Find free videos on “typescript tutorial for beginners why typescript” on YouTube ↗
In real life: Renaming a field across a large app
A logistics company renamed the field deliveryDate to expectedDelivery in its API. In the TypeScript front end, changing the type definition immediately showed red errors in all 47 places that used the old name, so the team fixed them before release. In an older plain-JavaScript admin panel, three pages silently showed "undefined" for a week.
interface Shipment {
id: string;
expectedDelivery: string; // was deliveryDate
}
function label(s: Shipment) {
return `${s.id}: ${s.expectedDelivery}`; // s.deliveryDate would now be an error
}Practice (0/3 done)
Add types and fix the bug: totalPrice(price: number, qty: number): number should return price × qty, but it currently adds them.
What does the browser actually run when you use TypeScript?
Types are erased at run time, so data from outside must be checked by code. Write parseQty(input: unknown): number that returns the input if it is a whole number from 1 to 99, and throws an Error "Invalid quantity" otherwise.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Basic types and inferenceTypeScript basics · same module
- Object types, interfaces and unionsTypeScript basics · same module
- GenericsTypeScript basics · same module
- Why TypeScriptFrontend Web Development · TypeScript basics
- TypeScript in real projectsFrontend Web Development · TypeScript basics
- Typing functions and objectsFrontend Web Development · TypeScript basics
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
When does TypeScript report type errors?
Answer: Before running, when you compile or in the editor
Type checking happens at compile time.
What does "type erasure" mean?
Answer: Types are deleted from the output JavaScript
tsc removes annotations; they do not exist at run time.
Which tsconfig option should new projects turn on?
Answer: "strict": true
strict enables the full set of useful checks.
let n = 5; n = "five"; In TypeScript this is…
Answer: An error: string is not assignable to number
n was inferred as number.
What does the TypeScript compiler (tsc) produce from your .ts files?Related
Answer: Plain JavaScript with the types removed
tsc checks the types and writes JavaScript without them, because browsers and Node.js run JavaScript.
From Why TypeScript
In a Vite project, why does tsconfig.json often have "noEmit": true?Related
Answer: Because Vite builds the JavaScript; TypeScript is only used to check types
Vite strips types and bundles the code. tsc (or the editor) only needs to check, so it writes no files.
What does a return type of void mean?Related
Answer: The function does not return a useful value
void is for functions that do a job (like logging) and do not give back a value.
Where should an API key live?Related
Answer: In an environment variable / .env file that is not committed
Secrets stay out of the code and out of Git.
From Real project tooling
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “TypeScript basics” before its exam: Basic types and inference, Object types, interfaces and unions, Generics, Utility types and real-world TypeScript.
- Module 9 exam: TypeScript basics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functional patterns and testing. 61 topics left in the course before the final exam.