TypeScript vs JavaScript
In this page:
Typing Differences
JavaScript uses dynamic typing, so a variable can hold different kinds of values during execution. TypeScript allows developers to specify and check the expected type of a value.
Example: Typing Differences
let value: number = 10;
// value = "ten"; // TypeScript rejects this; plain JS would allow it
console.log(value);
Error Detection
JavaScript often discovers type-related problems while the program is running. TypeScript can identify many such problems during compilation, before the generated JavaScript is executed.
Example: Error Detection
function add(a: number, b: number): number {
return a + b;
}
// add(5, "10"); // caught at compile time, not at runtime
console.log(add(5, 10));
Compilation
JavaScript can usually be executed directly by a JavaScript runtime. TypeScript normally needs to be compiled or otherwise transformed into JavaScript before it can be executed by standard JavaScript runtimes.
Example: Compilation
let greeting: string = "Hello, TypeScript";
console.log(greeting);
// tsc compiles this .ts file into plain .js before any JS runtime executes it
Development Experience
TypeScript provides rich information about types to editors and development tools. This can improve autocomplete, navigation, refactoring, and error reporting while writing code.
Example: Development Experience
interface Product {
name: string;
price: number;
}
const item: Product = { name: "Pen", price: 2 };
console.log(item.price); // editor autocompletes .name and .price
Choosing TypeScript or JavaScript
JavaScript can be a simple choice for small scripts and projects where minimal setup is important. TypeScript is often preferred when stronger type checking, maintainability, and developer tooling are valuable.
Example: Choosing TypeScript or JavaScript
// Small script: plain JS is enough
console.log("Quick script, no types needed");
// Large app: TypeScript adds safety
interface Config { retries: number; }
const config: Config = { retries: 3 };
console.log(config.retries);
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: