What is TypeScript
In this page:
Understanding TypeScript
TypeScript is a superset of JavaScript, which means valid JavaScript code can generally be used in a TypeScript file. TypeScript adds features such as type annotations, interfaces, and advanced type checking.
Example: Understanding TypeScript
let age: number = 25;
let city = "Delhi"; // plain JS-style code still works in TypeScript
console.log(age, city);
Static Type Checking
One of TypeScript's main benefits is static type checking. The compiler can detect when a value does not match the declared type before the program is executed.
Example: Static Type Checking
let age: number = 25;
// age = "twenty five"; // compiler catches this mismatch before running
console.log(typeof age, age);
TypeScript and JavaScript
TypeScript extends JavaScript rather than replacing it with a completely different runtime. TypeScript code is transformed into JavaScript that can run in browsers, Node.js, and other JavaScript environments.
Example: TypeScript and JavaScript
let message: string = "Compiled to plain JavaScript";
console.log(message);
// tsc removes ": string" and outputs: console.log(message);
Benefits of TypeScript
TypeScript can make larger applications easier to maintain by providing better editor support, clearer code, and earlier error detection. Types also make it easier for developers to understand what values functions and variables are expected to use.
Example: Benefits of TypeScript
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: "Asha" };
console.log(user.id, user.name);
When to Use TypeScript
TypeScript is especially useful for medium and large applications where many files, developers, and data structures need to work together. It can also be used for smaller projects when you want stronger type checking and better development tools.
Example: When to Use TypeScript
interface Order {
id: number;
total: number;
}
function printOrder(order: Order): void {
console.log(`Order ${order.id}: $${order.total}`);
}
printOrder({ id: 101, total: 49.99 });
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: