ObjectValidator
See source codeTable of contents
Extends Validator<Shape>
.
class ObjectValidator<Shape extends object> extends Validator<Shape> {}
Constructor
Constructs a new instance of the ObjectValidator
class
Parameters
Name | Description |
---|---|
|
|
|
|
Properties
config
readonly config: {
readonly [K in keyof Shape]: Validatable<Shape[K]>
}
validateUsingKnownGoodVersionFn
readonly validateUsingKnownGoodVersionFn?:
| undefined
| ValidatorUsingKnownGoodVersionFn<T, T>
validationFn
readonly validationFn: ValidatorFn<T>
Methods
allowUnknownProperties()
allowUnknownProperties(): ObjectValidator<Shape>
check()
Refine this validation with an additional check that doesn't change the resulting value.
check(name: string, checkFn: (value: T) => void): Validator<T>
Example
const numberLessThan10Validator = T.number.check((value) => {
if (value >= 10) {
throw new ValidationError(`Expected number less than 10, got ${value}`)
}
})
Parameters
Name | Description |
---|---|
|
|
|
|
Returns
Validator<T>
extend()
Extend an object validator by adding additional properties.
extend<Extension extends Record<string, unknown>>(extension: {
readonly [K in keyof Extension]: Validatable<Extension[K]>
}): ObjectValidator<Shape & Extension>
Example
const animalValidator = T.object({
name: T.string,
})
const catValidator = animalValidator.extend({
meowVolume: T.number,
})
Parameters
Name | Description |
---|---|
|
|
Returns
ObjectValidator<Shape & Extension>
isValid()
Checks that the passed value is of the correct type.
isValid(value: unknown): value is T
Parameters
Name | Description |
---|---|
|
|
Returns
value is T
nullable()
Returns a new validator that also accepts null or undefined. The resulting value will always be null.
nullable(): Validator<null | T>
optional()
Returns a new validator that also accepts null or undefined. The resulting value will always be null.
optional(): Validator<T | undefined>
refine()
Refine this validation to a new type. The passed-in validation function should throw an error if the value can't be converted to the new type, or return the new type otherwise.
refine<U>(otherValidationFn: (value: T) => U): Validator<U>
Parameters
Name | Description |
---|---|
|
|
Returns
Validator<U>
validate()
Asserts that the passed value is of the correct type and returns it. The returned value is guaranteed to be referentially equal to the passed value.
validate(value: unknown): T
Parameters
Name | Description |
---|---|
|
|
Returns
T
validateUsingKnownGoodVersion()
validateUsingKnownGoodVersion(knownGoodValue: T, newValue: unknown): T
Parameters
Name | Description |
---|---|
|
|
|
|
Returns
T