Skip to content

parseKeyOf

Parses a value into a valid key of a given object or enum. This parser uses the validateKeyOf semantic validator to ensure that the provided key exists as an own property of the target object.

The parser never throws and never mutates input. It returns a structured ParseResult<keyof T> describing success or failure.

Signature

function parseKeyOf<T extends Record<PropertyKey, unknown>>(
    key: unknown,
    obj: T
): ParseResult<keyof T>

Behavior

  • Accepts keys that:
  • Are strings or numbers.
  • Exist as own properties of the target object.
  • Rejects:
  • Missing keys.
  • Invalid key types.
  • Non-object targets.
  • Never mutates input.
  • Never throws.

Returns

  • ok: true: And the validated key when parsing succeeds.
  • ok: false, value: null: And a list of issues when parsing fails.

Examples

parseKeyOf("a", { a: 1, b: 2 })
// { ok: true, value: "a", issues: [] }

parseKeyOf("z", { a: 1, b: 2 })
// { ok: false, value: null, issues: ["Value is not a valid key of the provided object"] }

enum Colors { Red = "red", Blue = "blue" }
parseKeyOf("Red", Colors)
// { ok: true, value: "Red", issues: [] }

Notes

  • Works with objects, records, and TypeScript enums.
  • This parser is pure, side-effect-free, and safe for all runtime environments.