Careeroza
How TypeScript Compiles to JavaScript
The Compile Step
index.ts ---> tsc ---> 1. type check (report errors)
2. remove types, convert syntax to target
---> index.js ---> node / browser runs itThe compiler does two separate jobs: it checks types and it emits JavaScript. Types never reach the JavaScript output, so they cost nothing at runtime.
Input and Output
TypeScript input:
interface Product {
name: string;
price: number;
}
const p: Product = { name: "Pen", price: 20 };
const total = (qty: number): number => p.price * qty;JavaScript output (target ES2022): the interface and all annotations are gone.
"use strict";
const p = { name: "Pen", price: 20 };
const total = (qty) => p.price * qty;Types Disappear at Runtime
Example
Because types are removed, you cannot ask "is this an interface?" at runtime. You check real JavaScript values (typeof, properties) instead.
interface Product {
name: string;
price: number;
}
const p: Product = { name: "Pen", price: 20 };
console.log(typeof p);
console.log(typeof p.price);
console.log(JSON.stringify(p));Output
object
number
{"name":"Pen","price":20}Note: By default tsc still writes the JavaScript file even when there are type errors. Set "noEmitOnError": true to stop that.