← العودة إلى الدورة: TypeScript from scratch

Enums, alternatives and week review

الفيديو قريبًا

An enum is a way to give names to a fixed set of related values: the states of an order, the days of the week, the levels of a log. TypeScript has the enum keyword, which does not exist in JavaScript. That makes it special: it is one of the few language features that generates real code when compiling, instead of being erased. For that reason many teams now prefer lighter alternatives. Knowing both options lets you read any project and choose wisely.

Numeric and string enums

By default, the members of an enum are numbers starting at 0. A numeric enum has an oddity: it accepts any number, even one that does not match a member, which weakens safety. String enums, where you assign a string to each member, are safer and more readable when debugging, because you see 'PAID' instead of a mysterious 2. If you use enum, prefer the string variant.

typescript
enum OrderStatus {
  Pending = 'PENDING',
  Paid = 'PAID',
  Shipped = 'SHIPPED',
}

function label(status: OrderStatus): string {
  switch (status) {
    case OrderStatus.Pending:
      return 'Waiting for payment';
    case OrderStatus.Paid:
      return 'Payment received';
    case OrderStatus.Shipped:
      return 'On its way';
  }
}

console.log(label(OrderStatus.Paid)); // Payment received
// label('PAID'); // error: Argument of type '"PAID"' is not assignable to parameter of type 'OrderStatus'

The alternative: as const objects and unions

The most popular alternative is a union of literals, which you already know, or an object marked with as const from which the union is derived. The union generates no JavaScript, is compatible with plain values arriving from an API and works with any tool that only erases types. The as const object also gives you a place to write Status.Paid with autocompletion and a runtime value you can iterate. To derive the type you use keyof and typeof, which you will master in week 7; today it is enough to copy the pattern.

typescript
const Status = {
  Pending: 'PENDING',
  Paid: 'PAID',
  Shipped: 'SHIPPED',
} as const;

type Status = (typeof Status)[keyof typeof Status]; // 'PENDING' | 'PAID' | 'SHIPPED'

function isFinal(status: Status): boolean {
  return status === Status.Shipped;
}

const incoming: Status = 'PAID'; // a plain string works too
console.log(isFinal(incoming), Object.values(Status));

Week review

This week you modeled data: objects with type and interface, optional and readonly properties, extending shapes, typed arrays, tuples, read-only collections, dynamic keys and sets of values with enums and alternatives. Practice combining them: the next exercise models a small inventory with everything you saw and is good preparation for the generics of week 5.

A good way to review is to reread your code from the week looking for decisions. Did you choose type or interface and can you explain why? Is there any string that would be better as a union of literals? Any array that should be readonly because the function does not modify it? Any tuple that is really a disguised object? Asking yourself this is much more valuable than memorizing syntax, because it develops the design judgment that distinguishes someone who uses TypeScript from someone who merely suffers it.

اختبر ما تعلمته

السؤال 1 من 6

What can a type express that an interface cannot?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →