validateValueOf
Validates that a value exists among the values of a given object or enum.
This helper checks whether a provided value exists in the set of own property values of a target object or TypeScript enum. It never mutates input and never throws.
It uses the isValueOf function internally to perform runtime-safe checks.
Signature
function validateValueOf<T>(
value: unknown,
obj: Record<PropertyKey, T>
): T | null
Parameters
| Name | Data type | Description |
|---|---|---|
| value | unknown |
The value to validate. |
| object | T |
The enum or object who values are valid. |
Returns
One of:
- The original value if it exists among the object values (
T). null: If the value does not exist.
Behavior
- Accepts any value for validation.
- Rejects values that are not present among the values in
obj. - Works with both plain objects and TypeScript enums.
- Never throws and never mutates input.
Examples
const obj = { a: 1, b: 2 };
validateValueOf(1, obj) // 1
validateValueOf(2, obj) // 2
validateValueOf(3, obj) // null
validateValueOf("1", obj as unknown as Record<string, unknown>) // null
enum Colors { Red = "RED", Blue = "BLUE" }
validateValueOf("RED", Colors as unknown as Record<PropertyKey, unknown>) // "RED"
validateValueOf("BLUE", Colors as unknown as Record<PropertyKey, unknown>) // "BLUE"
validateValueOf("GREEN", Colors as unknown as Record<PropertyKey, unknown>) // null
Notes
- This helper validates values, not keys.
- Use validateKeyOf if you want to validate keys instead of values.
- Ideal for validating enum values, configuration values, or any object’s set of acceptable constants.
- Fully TypeScript-safe and compatible with objects and enums.