Elwin's Blog

an activist who likes to think

front cover

Notes on using Typescript: with design pattern

Posted on

I have been using Typescript for some time, but still feels something absent on learning it, then I notice that beyond the basic syntax, I'm not familiar with the design pattern of Typescript. Sure, It's not actually a language, but since it's so widely used in my work, I feel that I should invest more time in learning the advanced usage of it.

I'll start from the definition of some less common features:

Enums:

  1. Used for values that are closely related.
  2. They are known at compile time.

Tuple:

Rarely used, since they don't have keys to describe what value it holds. Can be used to describe data type from a CSV file(each row contains a different data type).

Abstract:

Used to delay a method implementation at a later stage(ex: at a child class)

Generic:

The constraint of it and how to fix it:

When you are using a property or a method that belongs to a specific data type, you'll see an error.

Fix: use extends to add the desired method or props to the generic type. check the code below for example:

function printHousesOrCars<T extends Printable>(arr: T[]): void {
  for (let i = 0; i < arr.length; i++) {
    arr[i].print();
  }
}

Utility Type

Omit, Pick is useful to interfaces that contain more than a few properties, for example, check this snippet from the official doc:

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};
 
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
 
const todoInfo: TodoInfo = {
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
};

There are other utility types that can be used too, check the official doc here