Skip to main content

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

Enum.tryGetKeyByNumber() method

Returns an enum string key, given its numeric value. Returns undefined if no matching value is found.

Signature:
static tryGetKeyByNumber<TEnumValue, TEnumObject extends {
[key: string]: TEnumValue;
}>(enumObject: TEnumObject, value: number): keyof typeof enumObject | undefined;

Parameters

ParameterTypeDescription
enumObjectTEnumObject
valuenumber
Returns:

keyof typeof enumObject | undefined

Remarks

The TypeScript compiler only creates a reverse mapping for enum members whose value is numeric. For example:

enum E {
A = 1,
B = 'c'
}

// Prints "A"
console.log(E[1]);

// Prints "undefined"
console.log(E["c"]);

Example

Example usage:

enum Colors {
Red = 1,
Blue = 'blue'
}

// Prints "Red"
console.log(Enum.tryGetKeyByNumber(Colors, 1));

// Prints "undefined"
console.log(Enum.tryGetKeyByNumber(Colors, -1));