TypeScript Handbook
TypeScript Handbook
1. Introduction to TypeScript
2. Getting Started
Installation Instructions
● Install TypeScript globally via npm: npm install -g typescript.
● This installs the TypeScript compiler (tsc) globally, allowing you to
compile TypeScript files anywhere on your system.
Setting up a New Project
● Initialize a new TypeScript project using tsc --init. This creates a
tsconfig.json file which specifies compiler options and project settings.
● Configure tsconfig.json according to your project requirements, such as
specifying target ECMAScript version, output directory, and module
system.
Integrating with Existing Projects
● Rename existing JavaScript files to TypeScript files (.js to .ts) to start
using TypeScript.
● Begin adding type annotations gradually to existing JavaScript code,
improving type safety and code quality over time.
4. Static Typing
6. Classes
Object-Oriented Programming
● Classes in TypeScript allow developers to use object-oriented
programming concepts such as encapsulation, inheritance, and
polymorphism.
Constructors and Access Modifiers
● Constructors are special methods used for initializing class instances.
Access modifiers (public, private, protected) control the visibility of class
members.
● Example:
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number) {
console.log(`${this.name} moved ${distance} meters.`);
}
}
7. Generics
Introduction
● Generics allow developers to create reusable components that can work
with a variety of data types.
● They provide a way to define functions and classes with placeholders for
types.
Generic Constraints
● Generic types can be constrained to specific types or structures using type
constraints. This ensures type safety and enables more precise type
checking.
● Example:
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Error: Property 'length' does not exist on
type 'T'.
return arg;
}