TypeScript
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
What is TypeScript?
Section titled “What is TypeScript?”TypeScript adds static typing to JavaScript. This means you can define the types of variables, function parameters, and return values, allowing the compiler to catch errors before your code even runs.
- Superset of JavaScript: All valid JavaScript code is also valid TypeScript.
- Transpilation: Browsers cannot run TypeScript directly. It must be “transpiled” into standard JavaScript.
- Enhanced Productivity: Provides better autocompletion, refactoring, and documentation in IDEs like VS Code.
Basic Types
Section titled “Basic Types”let isDone: boolean = false;let age: number = 42;let firstName: string = 'Jane';let numbers: number[] = [1, 2, 3];let mixed: any = 'could be anything'; // Use sparingly!Functions
Section titled “Functions”Types for parameters and return values:
function add(a: number, b: number): number { return a + b;}
const result = add(10, 20); // 30// add("10", 20); // Error: Argument of type 'string' is not assignable to 'number'Interfaces and Objects
Section titled “Interfaces and Objects”Defining the “shape” of an object:
interface User { id: number; username: string; email?: string; // Optional property}
const user: User = { id: 1, username: 'jdoe',};A way to define a set of named constants:
enum Direction { Up, Down, Left, Right,}
let move: Direction = Direction.Up;Why use TypeScript?
Section titled “Why use TypeScript?”- Catch Bugs Early: Static typing identifies common errors (like typos or null checks) during development.
- Easier Refactoring: Confidently rename variables or change function signatures across large codebases.
- Readability: Code becomes self-documenting as types explain what kind of data is being passed around.