Skip to content

objectGuard() ​

ts
function objectGuard<T>(schema): Guard<OptionalKeys<T> extends undefined ? T : WithOptionalFields<T>>

Objects have a fixed set of properties of different types.

See ​

objectGuardCompiled for just-in-time compiled version of this function.

Type Parameters ​

Type Parameter
T extends Record<string, unknown>

Parameters ​

ParameterTypeDescription
schema{ [K in string | number | symbol]-?: Object extends Pick<T, K> ? OptionalGuard<T[K]> : Guard<T[K]> }maps keys to validation functions.

Returns ​

Guard<OptionalKeys<T> extends undefined ? T : WithOptionalFields<T>>

Examples ​

ts
Object with both required and optional properties:
const isUser = objectGuard({
  id: isNumber,
  uid: isString,
  active: isBoolean,
  email: optional(isString),
})

Note that optional properties will be inferred as required properties that can be assigned undefined. See Infer > limitations for in-depth information.

Annotate explicitly:

ts
type User = {
  id: number
  name: string
}

const isUser = object<User>({
  id: isNumber,
  name: isString,
})

objectGuardCompiled() ​

ts
function objectGuardCompiled<T>(schema): Guard<OptionalKeys<T> extends undefined ? T : WithOptionalFields<T>>

Same as objectGuard, but performs just-in-time (JIT) compilation with the Function constructor, which greatly increases the execution speed of the validation. However, the JIT compilation is slow and gets executed at the time when the validation function is constructed. When using this function at the module level, it is recommended to wrap it in lazy to defer the JIT compilation to when the validation function is called for the first time. This function will be blocked in environments where the Function constructor is blocked; for example, when the Content-Security-Policy policy is set without the 'unsafe-eval' directive.

Example ​

Defer the JIT compilation to when the validation function is called for the first time.

ts
const isUser = lazy(() => objectGuardCompiled({
 id: isNumber,
 name: isString,
})

See ​

objectGuard for a non-just-in-time compiled version of this function.

Type Parameters ​

Type Parameter
T extends Record<string, unknown>

Parameters ​

ParameterTypeDescription
schema{ [K in string | number | symbol]-?: Object extends Pick<T, K> ? OptionalGuard<T[K]> : Guard<T[K]> }maps keys to validation functions.

Returns ​

Guard<OptionalKeys<T> extends undefined ? T : WithOptionalFields<T>>