Enum in typescript

moseskarunia

Moses Karunia

Posted on October 31, 2019

Enum in typescript

Changelog:

  • 6 Nov 2019: Added type for better developer experience.

I know we can use typescript's enum, but, the difficulty arises when I'm receiving string in REST, and want to validate the property value in the request.

This is the way I write my enums:

// ===== DECLARATION =====

type TerrainEnum = 'MEADOW' | 'OCEAN' | 'FOREST';

class Terrain {
  public static readonly Meadow = 'MEADOW';
  public static readonly Ocean = 'OCEAN';
  public static readonly Forest = 'FOREST';

  public static isValid = (value: string): boolean => (
    value === Terrain.Meadow ||
    value === Terrain.Ocean ||
    value === Terrain.Forest
  );
}

// ===== USAGE =====

// Validate
Terrain.isValid(value);

// In function parameter
const myFunction = (terrain: TerrainEnum): void => {}

Enter fullscreen mode Exit fullscreen mode

I think this way you have a built-in input validations, simply by calling isValid().

I'm interested in what you guys think. Maybe we can find any better option out there.

So, what's your preferred way to write enums? And what's the reason behind yours?

💖 đŸ’Ș 🙅 đŸš©
moseskarunia
Moses Karunia

Posted on October 31, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related