TypeScript Types

Page 2 of 4

Custom Types (Type & Interface)

Create your own complex types using `type` and `interface`.

TypeScript allows you to define your own types using the type and interface keywords. This is fundamental for creating well-structured and reusable data models in your application.

interface

An interface is a way to define the shape of an object. It can be extended by other interfaces and implemented by classes.

interface User {
  id: number;
  name: string;
  isActive: boolean;
}

const user: User = { id: 1, name: "Leanne Graham", isActive: true };

type

A type alias can also describe an object shape, but it is more versatile. It can represent primitive types, unions, tuples, and more complex combinations.

type Point = {
  x: number;
  y: number;
};

type ID = string | number; // Union type

Notes

  • Use interface when defining the shape of objects or classes. Prefer interface over type for object shapes because it offers better error messages and can be extended.
  • Use type for defining union types, tuples, or other complex types.

Function

Describes the shape of a function, including its parameters and return value.

TypeScript allows you to define the types for a function’s parameters and its return value. This provides strong type safety, ensuring that you call functions with the correct arguments and handle their outputs correctly.

Example of usage

// Named function with typed parameters and return value
function add(x: number, y: number): number {
  return x + y;
}

// Arrow function syntax
const subtract = (x: number, y: number): number => {
  return x - y;
};

Notes

  • The return type can often be inferred by TypeScript, but explicitly defining it is a good practice for clarity.
  • You can define optional parameters using a ? after the parameter name.

Never

Represents the type of values that never occur.

The never type is used for values that should never exist. For instance, never is the return type for a function expression that always throws an exception or one that never returns. Variables also acquire the type never when narrowed by any type guards that can never be true.

Example of usage

// Function that never returns
function error(message: string): never {
  throw new Error(message);
}

// Function with an infinite loop
function infiniteLoop(): never {
  while (true) {}
}

Notes

  • The never type is a subtype of, and assignable to, every type.
  • However, no type is a subtype of, or assignable to, never (except never itself).