Lädt...


🔧 Simplifying Union Types and Arrays in TypeScript


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

When working with TypeScript, you might find yourself needing to define a union type and an array containing all of the possible values of that type. A common approach is to write something like this:

type Taste = 'しょうゆ' | 'みそ' | 'とんこつ';
const tastes = ['しょうゆ', 'みそ', 'とんこつ'];

At first glance, this seems fine. However, there's a hidden problem here: every time you want to change or add an option, you need to update both the Taste union type and the tastes array. This duplication of effort can lead to mistakes and makes maintaining the code more tedious.

Luckily, there's a way to simplify this by reducing redundancy. By using the as const assertion and typeof in TypeScript, you can consolidate the definition of both the union type and the array into one place. Here's how you can refactor the above code:

const tastes = ['しょうゆ', 'みそ', 'とんこつ'] as const;
type Taste = (typeof tastes)[number];

This approach has several benefits:

  1. Single Source of Truth:

    You only define the list of values once, in the tastes array. The Taste type is automatically derived from this array, so if you ever need to update the list, you only have to do it in one place.

  2. Type Safety:

    By using as const, TypeScript treats the tastes array as a tuple with literal types instead of just a string array. This ensures that the Taste type remains accurate and aligned with the values in tastes.

  3. Better Maintenance:

    Since the Taste type is generated from the array, there’s no risk of mismatch between the type and the actual values. This reduces the potential for bugs and makes the code easier to maintain.

Example Use Case

Now, whenever you use the Taste type in your code, it’s guaranteed to match the values in the tastes array:

function describeTaste(taste: Taste): string {
  switch (taste) {
    case 'しょうゆ':
      return 'Savory soy sauce flavor.';
    case 'みそ':
      return 'Rich miso flavor.';
    case 'とんこつ':
      return 'Creamy pork broth flavor.';
    default:
      return 'Unknown taste';
  }
}

const allTastes: Taste[] = tastes; // Safe, because they match the type!

This pattern not only improves your code’s readability but also ensures that it’s less error-prone, especially when dealing with multiple values that need to be kept in sync.

By embracing this strategy, you can make your TypeScript code more maintainable and scalable. This is particularly useful when you're dealing with large sets of values or when your codebase grows over time.

...

🔧 Simplifying Union Types and Arrays in TypeScript


📈 58.95 Punkte
🔧 Programmierung

🔧 PHP 8 News: Union Types and Mixed Types


📈 32.72 Punkte
🔧 Programmierung

🔧 Exploring the Power of Union and Intersection Types in TypeScript


📈 31.98 Punkte
🔧 Programmierung

🔧 How to use typescript enums to store Union Types and access them during runtime


📈 31.98 Punkte
🔧 Programmierung

📰 TypeScript 3.5 verbessert das Prüfen von Union Types


📈 30.66 Punkte
📰 IT Nachrichten

🔧 How to Simplify Your Code with TypeScript Discriminated Union Types


📈 30.66 Punkte
🔧 Programmierung

🔧 C# Tip: Use var for Obvious Types, but Prefer Explicit Types for Ambiguous Types


📈 29.56 Punkte
🔧 Programmierung

🔧 Arrays.mismatch() and Arrays.compare() in Java


📈 29.25 Punkte
🔧 Programmierung

🔧 Optimizing a TypeScript Curry Function: From Static Types to Variadic Types


📈 28.82 Punkte
🔧 Programmierung

🔧 We are simplifying (literals(arrays and objects)) in Js.


📈 28.29 Punkte
🔧 Programmierung

🔧 How Types Work in TypeScript – Explained with JavaScript + TypeScript Code


📈 28.07 Punkte
🔧 Programmierung

🔧 Union of Two Sorted Arrays


📈 25.67 Punkte
🔧 Programmierung

🔧 Disjoint set graph with union by rank and union by size


📈 24.71 Punkte
🔧 Programmierung

🔧 Difference between UNION and UNION ALL in SQL


📈 24.71 Punkte
🔧 Programmierung

🔧 Simplifying Authentication with JWT, TypeScript and Fastify


📈 23.43 Punkte
🔧 Programmierung

🔧 Simplifying Type Narrowing and Guards in TypeScript


📈 23.43 Punkte
🔧 Programmierung

📰 Bundestagswahl 2017: Union und SPD verlieren stark - Union stärkste, AfD drittstärkste Kraft


📈 23.4 Punkte
📰 IT Nachrichten

📰 YouTubers Union Teams With Actual Labor Union To Pressure YouTube


📈 23.4 Punkte
📰 IT Security Nachrichten

📰 Union Berlin gegen Royale Union Saint-Gilloise gratis im Live-Stream: So seht ihr das Spiel


📈 23.4 Punkte
📰 IT Nachrichten

🍏 Union Organizers Plan Class Action Lawsuit Against Apple for Union-Busting Tactics


📈 23.4 Punkte
🍏 iOS / Mac OS

🐧 TypeScript: Arrays erstellen und manipulieren


📈 23.08 Punkte
🐧 Server

🔧 Simplifying State Updates for Reference Types


📈 22.86 Punkte
🔧 Programmierung

🔧 Master Union And Intersection in Typescript


📈 22.12 Punkte
🔧 Programmierung

🔧 Union and intersection type in Typescript


📈 22.12 Punkte
🔧 Programmierung

🔧 Simplifying Imports with TypeScript Path Aliases in Umbraco v14


📈 22.12 Punkte
🔧 Programmierung

🔧 Clawject: Simplifying Dependency Injection in TypeScript


📈 22.12 Punkte
🔧 Programmierung

🔧 From React to TypeScript, Simplifying Migration with ts-migrate


📈 22.12 Punkte
🔧 Programmierung

🔧 Simplifying Async Error Handling in TypeScript


📈 22.12 Punkte
🔧 Programmierung

🔧 TypeScript and ReactMarkdown: A Tale of Types, Tears, and Triumph


📈 21.58 Punkte
🔧 Programmierung

matomo