Enum in typescript
Moses Karunia
Posted on October 31, 2019
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 => {}
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?
đ đȘ đ
đ©
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
discuss đWhatâs New in TypeScript: Essential Updates, Advantages, and Tips for 2024
October 31, 2024
webdev JS being weird again: forcibly convert synchronous statement to asynchronous with async function
October 26, 2023