Skip to content

Instantly share code, notes, and snippets.

@coltenkrauter
Last active May 26, 2024 02:16
Show Gist options
  • Save coltenkrauter/5db8629e3951b4b1970e0bbbe67452f5 to your computer and use it in GitHub Desktop.
Save coltenkrauter/5db8629e3951b4b1970e0bbbe67452f5 to your computer and use it in GitHub Desktop.
10 Ways to Use TypeScript Types

10 Ways to Use TypeScript Types

Table of Contents

  1. Basic Types
  2. Union Types
  3. Intersection Types
  4. Type Aliases
  5. Literal Types
  6. Nullable Types
  7. Type Assertions
  8. Function Types
  9. Tuple Types
  10. Mapped Types
  11. Types Vs Interfaces

1. Basic Types

Demonstrates the basic types available in TypeScript.

let employeeName: string = "Jim Halpert";
let age: number = 32;
let isManager: boolean = false;

const employee: { name: string; age: number; isManager: boolean } = {
  name: "Pam Beesly",
  age: 30,
  isManager: false
};

2. Union Types

Allows a variable to be one of several types.

let managerOrEmployee: string | boolean;

managerOrEmployee = "Michael Scott";
managerOrEmployee = true;

3. Intersection Types

Combines multiple types into one.

type PersonalInfo = {
  name: string;
  age: number;
};

type JobInfo = {
  title: string;
  department: string;
};

type Employee = PersonalInfo & JobInfo;

const stanley: Employee = {
  name: "Stanley Hudson",
  age: 45,
  title: "Sales Representative",
  department: "Sales"
};

4. Type Aliases

Creates a new name for a type.

type EmployeeName = string;
type EmployeeAge = number;

const angela: { name: EmployeeName; age: EmployeeAge } = {
  name: "Angela Martin",
  age: 37
};

5. Literal Types

Specifies exact values a variable can hold.

type Department = "HR" | "Sales" | "Accounting";

const kevin: { name: string; department: Department } = {
  name: "Kevin Malone",
  department: "Accounting"
};

6. Nullable Types

Allows a type to also be null or undefined.

let creedNotes: string | null = "Top-secret document";
creedNotes = null;

7. Type Assertions

Forces a variable to be treated as a specific type.

let customerFeedback: any = "Great service!";
let feedbackLength: number = (customerFeedback as string).length;

8. Function Types

Describes types for functions, including parameters and return types.

type Greet = (name: string) => string;

const greetEmployee: Greet = (name: string) => {
  return `Hello, ${name}`;
};

9. Tuple Types

Defines an array with fixed types and length.

let dwightInfo: [string, number, boolean] = ["Dwight Schrute", 38, true];

10. Mapped Types

Creates new types by transforming existing ones.

type Role = "admin" | "editor" | "viewer";

type Permissions = {
  [role in Role]: boolean;
};

const rolePermissions: Permissions = {
  admin: true,
  editor: true,
  viewer: false
};

Types Vs Interfaces

Types and interfaces in TypeScript serve different purposes and have distinct use cases. Interfaces are primarily used to define the shape of objects or classes and support declaration merging, making them ideal for object-oriented programming and extending third-party libraries. Types, on the other hand, are more versatile, capable of representing primitives, unions, intersections, and complex type constructions. They are suitable for creating complex types, utility types, and working with a broader range of type definitions. Use interfaces for defining object structures and when declaration merging is needed, and use types for complex type definitions, working with primitives, and creating utility types.

Use Interfaces:

  • Object Shape Definition:

    • Use interfaces when defining the structure of an object or a class. Interfaces are specifically designed for this purpose and are more readable and conventional in the context of object-oriented programming.
  • Declaration Merging:

    • Interfaces can be merged, meaning you can declare the same interface multiple times, and TypeScript will combine them into a single interface definition. This is useful for extending the capabilities of third-party libraries or organizing your code.

Use Types:

  • Complex Type Definitions:

    • Use types when you need to define more complex types that go beyond the shape of an object. This includes union types, intersection types, and tuples.
  • Working with Primitives and Non-Object Types:

    • Types are more versatile than interfaces as they can represent any kind of type, including primitives (string, number, boolean), unions, and intersections. This makes them suitable for a broader range of type definitions.
  • Utility Types and Mapped Types:

    • Use types when working with utility types or mapped types to transform existing types into new ones.

This Gist was created with the assistance of ChatGPT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment