RoadmapShopEvents
Skip to main content

Home > @rushstack/node-core-library > Enum

Enum class

A helper for looking up TypeScript enum keys/values.

Signature:
export declare class Enum

Remarks

TypeScript enums implement a lookup table for mapping between their keys and values:

enum Colors {
Red = 1
}

// Prints "Red"
console.log(Colors[1]);

// Prints "1"
console.log(Colors["Red]);

However the compiler's "noImplicitAny" validation has trouble with these mappings, because there are so many possible types for the map elements:

function f(s: string): Colors | undefined {
// (TS 7015) Element implicitly has an 'any' type because
// index expression is not of type 'number'.
return Colors[s];
}

The Enum helper provides a more specific, strongly typed way to access members:

function f(s: string): Colors | undefined {
return Enum.tryGetValueByKey(Colors, s);
}

Methods

MethodModifiersDescription
getKeyByNumber(enumObject, value)staticThis API is similar to Enum.tryGetKeyByNumber() , except that it throws an exception if the key is undefined.
getValueByKey(enumObject, key)staticThis API is similar to Enum.tryGetValueByKey() , except that it throws an exception if the key is undefined.
tryGetKeyByNumber(enumObject, value)staticReturns an enum string key, given its numeric value. Returns undefined if no matching value is found.
tryGetValueByKey(enumObject, key)staticReturns an enum value, given its key. Returns undefined if no matching key is found.