validateKeyOf
Validates that a value is a key of a given object or enum.
This helper checks whether a provided value (string or number) exists as an own property key in a target object or TypeScript enum. It never mutates input and never throws.
It uses the isKeyOf type guard internally to ensure strict, predictable behavior.
Signature
function validateKeyOf<T extends Record<PropertyKey, unknown>>(
key: unknown,
obj: T
): keyof 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 key if it exists in the object (
keyof T). null: If the key is invalid.
Behavior
- Accepts string or number keys.
- Rejects any other types (boolean,
null,undefined, objects, arrays). - Works with both plain objects and enums.
- Never throws and never mutates input.
Examples
const obj = { a: 1, b: 2 };
validateKeyOf("a", obj) // "a"
validateKeyOf("b", obj) // "b"
validateKeyOf("c", obj) // null
validateKeyOf(0, obj) // null
enum Colors { Red = "RED", Blue = "BLUE" }
validateKeyOf("Red", Colors) // "Red"
validateKeyOf("Green", Colors) // null
Notes
- This helper validates keys, not values.
- Use validateValueOf if you want to validate enum values instead of keys.
- Ideal for configuration validation, safe property access, and schema enforcement.