Skip to content

Commit 36ef889

Browse files
committed
Improve type inference for object and validateSchema
1 parent 50d76e2 commit 36ef889

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

‎src/json/index.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,16 @@ export function array<T>(validator: Validator<T>) {
7777
}
7878

7979
/** A validator for objects. */
80-
export function object(schema: Schema) {
80+
export function object<
81+
S extends Schema,
82+
T extends UnvalidatedObject<any> = FromSchema<S>,
83+
>(schema: S) {
8184
return {
8285
validate: (val: unknown) => {
83-
return isObject(val) && validateSchema(schema, val);
86+
return isObject(val) && validateSchema<S, T>(schema, val);
8487
},
8588
required: true,
86-
} as const satisfies Validator<FromSchema<typeof schema>>;
89+
} as const satisfies Validator<T>;
8790
}
8891

8992
/**
@@ -137,10 +140,10 @@ export type FromSchema<S extends Schema> = {
137140
* @param obj The object to validate.
138141
* @returns Asserts that `obj` is of the `schema`'s type if validation is successful.
139142
*/
140-
export function validateSchema<S extends Schema>(
141-
schema: S,
142-
obj: UnvalidatedObject<any>,
143-
): obj is FromSchema<S> {
143+
export function validateSchema<
144+
S extends Schema,
145+
T extends UnvalidatedObject<any> = FromSchema<S>,
146+
>(schema: S, obj: UnvalidatedObject<any>): obj is T {
144147
const result = checkSchema(schema, obj, { failFast: true });
145148
return result.valid;
146149
}

0 commit comments

Comments
 (0)