Beginner's guide to typescript
Introduction
TypeScript is a strongly-typed superset of JavaScript that adds optional static typing. Developed and maintained by Microsoft, it helps catch mistakes early, enables powerful tooling like intellisense, and can compile down to regular JavaScript.
Setting Up
Install TypeScript globally via npm:
npm install -g typescript
Basic Types
TypeScript provides several basic types:
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
Arrays and Tuples
Array and tuple types:
let list: number[] = [1, 2, 3];
let x: [string, number] = ['hello', 10];
Functions
Functions can have types for parameters and return values:
function add(x: number, y: number): number {
return x + y;
}
Interfaces
Interfaces allow you to define the shape of an object:
interface LabelledValue {
label: string;
}
function printLabel(obj: LabelledValue) {
console.log(obj.label);
}
Classes
TypeScript supports OOP features like classes, inheritance, and access modifiers:
class Animal {
private name: string;
constructor(name: string) { this.name = name; }
move(distance: number) {
console.log(`${this.name} moved ${distance}m.`);
}
}
Conclusion
TypeScript offers a comprehensive toolset for building large-scale JavaScript applications with the safety of static typing. Its integration with modern development tools makes it an excellent choice for web development. As you get deeper into TypeScript, you'll discover its advanced features like generics, namespaces, decorators, and more.