TypeScript
TypeScript is a statically-typed superset of JavaScript designed for large-scale application development. It adds optional static typing, interfaces, and advanced features like classes and modules to JavaScript, enabling developers to catch errors early and improve code maintainability. TypeScript integrates well with popular JavaScript frameworks and libraries, such as Angular and React, enhancing their development workflows.
Module 1: Introduction to TypeScript
TypeScript Basics
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.
let message: string = 'Hello, TypeScript!'; console.log(message);
Types in TypeScript
TypeScript supports many types like boolean, number, string, array, tuple, enum, any, void, null and undefined, never, and more.
let isBeginner: boolean = true; let total: number = 0; let name: string = 'TypeScript'; let list: number[] = [1, 2, 3]; let person: [string, number] = ['Chris', 22]; // Tuple
Functions in TypeScript
TypeScript provides static type checking for function parameters and return types.
function add(a: number, b: number): number { return a + b; } console.log(add(2, 3));
Module 2: Classes and Interfaces in TypeScript
Classes in TypeScript
TypeScript supports object-oriented programming and includes the concept of classes.
class Employee { private name: string; constructor(name: string) { this.name = name; } }
Inheritance in TypeScript
Inheritance is an important feature in TypeScript and allows us to create a child class that inherits fields and methods from a parent class.
class Manager extends Employee { constructor(managerName: string) { super(managerName); } }
Interfaces in TypeScript
Interfaces in TypeScript are used to tell the compiler what the shape of the JS object should look like. They are a powerful way to define 'contracts' both within your code and with code outside of your project.
interface Person { firstName: string; lastName: string; } function greet(person: Person) { return 'Hello ' + person.firstName + ' ' + person.lastName; }
Module 3: Advanced TypeScript Concepts
Generics in TypeScript
Generics are a tool for creating reusable components, by providing a way to create functions, classes and interfaces that work over a variety of types.
function identity<T>(arg: T): T { return arg; } let output = identity<string>('myString');
Decorators in TypeScript
Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.
function sealed(target) { Object.seal(target); Object.seal(target.prototype); } @sealed class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return 'Hello, ' + this.greeting; } }
Modules in TypeScript
Modules are TypeScript's way of organizing code. They can contain both code and declarations.
import { sayHello } from './greet'; console.log(sayHello('TypeScript'));