Skip to content

Commit

Permalink
fix: fix object schema type inference
Browse files Browse the repository at this point in the history
  • Loading branch information
ASafaeirad committed Apr 13, 2024
1 parent de998bf commit 445c0eb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
7 changes: 7 additions & 0 deletions src/Config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { InferType } from './InferType';
import type { Schema, SchemaOptions } from './Schema';
import { BooleanSchema, NumberSchema, StringSchema } from './Schema';
import { ObjectSchema } from './Schema/ObjectSchema';
import type { SchemaWithDefaultOptions } from './Schema/SchemaOptions';

type RequiredSchema<T extends Schema> = T & { isRequired: true };
Expand Down Expand Up @@ -47,6 +48,12 @@ export class Config<TSchema extends Record<string, Schema>> {
return new NumberSchema(options) as any;
}

static object<T extends Record<string, Schema>>(
schema: T,
): RequiredSchema<ObjectSchema<T>> {
return new ObjectSchema(schema) as any;
}

public get<TKey extends keyof TSchema>(key: TKey) {
return this.value[key] as InferType<TSchema>[TKey];
}
Expand Down
8 changes: 7 additions & 1 deletion src/InferType.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import type { Schema } from './Schema';

type Prettify<T> = {
[K in keyof T]: T[K];
} & {}; // eslint-disable-line @typescript-eslint/ban-types

export type InferType<T extends Record<string, Schema>> = {
[K in keyof T]: T[K]['isRequired'] extends true
[K in keyof T]: T[K] extends Schema<object>
? Prettify<InferType<T[K]['value']>>
: T[K]['isRequired'] extends true
? NonNullable<T[K]['value']>
: T[K]['value'];
};
7 changes: 2 additions & 5 deletions src/Schema/ObjectSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@ class ObjectGuard implements Guard<Record<string, Schema>> {
}
}

export class ObjectSchema<TInput = any> extends Schema<
TInput,
Record<string, unknown>
> {
export class ObjectSchema<TInput = any> extends Schema<TInput, TInput> {
constructor(schema: Record<string, Schema>) {
super({
typeConstructor: x => x as Record<string, unknown>,
typeConstructor: x => x as TInput,
type: 'object',
});
this.require();
Expand Down

0 comments on commit 445c0eb

Please sign in to comment.