TypeScript Essentials: A Guide to Static Typing in JavaScript
TypeScriptJavaScriptProgrammingStatic TypingWeb Development
TypeScript Essentials
TypeScript adds static typing to JavaScript, making your code more robust and maintainable. Let's explore the key concepts and features.
Basic Types
TypeScript provides several basic types:
// Basic type annotations
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42];
Interfaces
Interfaces define contracts in your code:
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
}
function createUser(user: User): User {
return user;
}
Type Aliases
Create custom types with type aliases:
type Point = {
x: number;
y: number;
};
type ID = string | number;
Generics
Write reusable, type-safe code with generics:
function identity<T>(arg: T): T {
return arg;
}
const num = identity<number>(42);
const str = identity<string>("hello");
Enums
Define a set of named constants:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
let movement: Direction = Direction.Up;
Type Assertions
Tell TypeScript about the specific type of a value:
let someValue: unknown = "hello world";
let strLength: number = (someValue as string).length;
Best Practices
- Always define proper types for variables and functions
- Use interfaces for object shapes
- Leverage type inference when possible
- Avoid using
any
type unless necessary - Use union types for flexibility
Advanced Features
Mapped Types
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Optional<T> = {
[P in keyof T]?: T[P];
};
Utility Types
// Built-in utility types
type PartialUser = Partial<User>;
type ReadonlyUser = Readonly<User>;
type PickedUser = Pick<User, "id" | "name">;
Conclusion
TypeScript's static typing system helps catch errors early, improves code maintainability, and provides better tooling support. Understanding these fundamentals will help you write more reliable and scalable applications.