Sub topic 1
Why TypeScript?
Prerequisites
You should know JavaScript functions, objects, and modules. You should also be comfortable with a terminal, npm, package.json, and running Node.js programs.
Why TypeScript?
JavaScript checks many mistakes only while a program runs. A function might expect a string but receive a number. A property might be missing from an object. These errors can reach users if tests do not exercise the failing path.
TypeScript adds static typing to JavaScript. Static typing means the compiler checks values and function calls before the program runs. TypeScript does not replace JavaScript. It adds a development-time checking layer and then produces JavaScript.
Static types in practice
A type annotation documents the value a function accepts and returns:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
console.log(greet(42));The second call is rejected because 42 is a number, not a string. Plain JavaScript would allow the call and might produce an incorrect result later.
TypeScript can infer many types, so you do not need to annotate every variable. Add annotations at boundaries such as function parameters, returned data, and external input. This gives the compiler useful information without making simple code noisy.
How TypeScript compiles: checking first, types erased
The TypeScript compiler, usually called tsc, performs two related tasks:
- It checks the TypeScript program for type errors.
- It emits JavaScript that a runtime such as Node.js or a browser can execute.
Type annotations do not exist in the emitted JavaScript. They are erased during compilation. TypeScript therefore does not add runtime type checks by itself.
A build can fail during checking even when JavaScript could technically be emitted. Treat type errors as feedback to resolve, not as runtime protections.
Installing TypeScript in a project
Install TypeScript locally as a development dependency. A local installation pins the compiler version for the project and keeps team and CI builds consistent.
mkdir ts-demo && cd ts-demo
npm init -y
npm install --save-dev typescript
npx tsc --versionnpx runs the project’s installed compiler. Later chapters will configure tsc with tsconfig.json and choose whether it should emit JavaScript or only check types.
Exercise
What happens to a string type annotation when TypeScript compiles the file?
Show answer
The annotation is erased. The generated JavaScript keeps the executable code but not that compile-time type information.