TypeScript Overview
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. It adds optional static typing to JavaScript, which helps catch errors early through a type system.
Key Features
- Static Typing: Optional type annotations catch errors at compile time.
- JavaScript Compatibility: All JavaScript code is valid TypeScript.
- Type Inference: Automatically infers types when not specified.
- Interfaces: Define contracts within your code.
- Generics: Create reusable, type-safe components.
- Modern JavaScript Features: Supports ES6+ features.
- Tooling Support: Excellent IDE support with IntelliSense.
Common Use Cases
Large-Scale Applications
Type safety helps manage complexity in large codebases.
Frontend Frameworks
Used with React, Angular, and Vue for type-safe UIs.
Node.js Backends
Type-safe server-side development.
Library Development
Better documentation and usage patterns with types.
Example Code
// TypeScript example demonstrating types and features
interface Person {
name: string;
age: number;
greet(): string;
}
class Employee implements Person {
constructor(
public name: string,
public age: number,
private salary: number
) {}
greet() {
return `Hello, my name is ${this.name}`;
}
getSalary() {
return this.salary;
}
}
// Generic function
function identity<T>(arg: T): T {
return arg;
}
// Async/await with types
async function fetchData<T>(url: string): Promise<T> {
const response = await fetch(url);
return await response.json() as T;
}
// Using the examples
const alice = new Employee("Alice", 30, 50000);
console.log(alice.greet());
const result = identity<string>("TypeScript is awesome");
console.log(result);
type User = { id: number; name: string };
fetchData<User[]>("https://api.example.com/users")
.then(users => console.log(users))
.catch(error => console.error(error));
// Tuple type
let coordinates: [number, number] = [10, 20];
console.log(coordinates);