Constants vs Enums in TypeScript

Published on 3/13/2024

Playground link

Using an object as a collection of constants:

const ERROR_TYPES = {
	NAME_VALIDATION: 'name_validation',
	LENGTH_VALIDATION: 'length_validation',
	UNKNOWN: 'unknown'
} as const;

// this creates: 'name_validation' | 'length_validation' | 'unknown'
type ERROR_STRINGS = (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES];

interface ErrorHandlersArgs {
	errorTypes: ERROR_STRINGS;
}

function errorHandler({ errorTypes }: ErrorHandlersArgs) {}

// call it
errorHandler({ errorTypes: ERROR_TYPES.NAME_VALIDATION });

or using enums

// compiles to an object at runtime
enum ERROR_TYPES {
	NAME_VALIDATION = 'name_validation',
	LENGTH_VALIDATION = 'length_validation',
	UNKNOWN = 'unknown'
}

interface ErrorHandlersArgs {
	// this creates: 'name_validation' | 'length_validation' | 'unknown'
	errorTypes: ERROR_TYPES;
}

function errorHandler({ errorTypes }: ErrorHandlersArgs) {}

// call it
errorHandler({ errorTypes: ERROR_TYPES.NAME_VALIDATION });