Thursday, August 22, 2024

TypeScript: type vs interface

 Interfaces vs Types in TypeScript - Stack Overflow

interface X {
    a: number;
    b: string;
}

type X = {
    a: number;
    b: string;
}


WHY?

Evolutionary Reasons: TypeScript has evolved over time, and different features have been introduced in different versions. 
  • interface has been part of TypeScript since its early versions, primarily for defining the shapes of objects. 
  • type aliases were introduced later to handle cases that interface couldn't easily represent, such as unions, intersections, and primitive types.



What is the difference between interface and type in TypeScript ? - GeeksforGeeks


Types vs. interfaces in TypeScript - LogRocket Blog


TypeScript: TS Playground - An online editor for exploring TypeScript and JavaScript


TypeScript: Documentation - Object Types


A Comprehensive Comparison of TypeScript Type vs Interface

Types in TypeScript are more flexible and can define primitive, intersection, union, tuple, or different types of data, while interfaces are used to describe the shape of an object.


Since Typescript 3.4, you could use as const and generate a union type from an array as follows

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] as const;
export type Color = typeof colors[number]; // 'red'|'orange'|'yellow'|'green'|'blue'|


How to use the keyof operator in TypeScript - LogRocket Blog
type Staff = {
 name: string;
 salary: number;
} 
type staffKeys = keyof Staff; // "name" | "salary"

Using the keyof typeof pattern

We often combine keyof and typeof together, to create a type that represents the keys of a specific object. This is particularly useful when you want to define a type based on the structure of an existing object.

Let’s say we have a userProfile object as shown here:

const userProfile = {
  username: 'john_doe',
  email: 'john@example.com',
  age: 30,
  isAdmin: false,
};

We can use the keyof typeof pattern to create a type representing the keys of this user profile object:

type UserProfileKeys = keyof typeof userProfile;
// type UserProfileKeys = "username" | "email" | "age" | "isAdmin"