Blog>
Snippets

Leveraging TypeScript Strong Typing Features

Use TypeScript's strong typing to define models and interfaces, thus improving code quality and maintainability.
interface User {
    id: number;
    name: string;
    email: string;
}

class UserService {
    private users: User[] = [];

    public addUser(user: User): void {
        this.users.push(user);
    }

    public getUserById(userId: number): User | undefined {
        return this.users.find(user => user.id === userId);
    }
}

const userService = new UserService();
userService.addUser({ id: 1, name: 'John Doe', email: 'john.doe@example.com' });
const user = userService.getUserById(1);

console.log(user);
This code snippet defines a TypeScript interface 'User' which is a strongly typed schema for user objects, enforcing that they must have 'id', 'name', and 'email' properties of specific types. A 'UserService' class is also defined with a private array to store 'User' objects and methods to add and retrieve users. Using these definitions, a 'userService' instance is created, a user is added using 'addUser', and later retrieved with 'getUserById', illustrating how TypeScript can ensure valid types are used throughout the application.