diff --git a/src/Config.ts b/src/Config.ts index 24fd217..4aed24b 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -1,38 +1,54 @@ import type { InferType } from './InferType'; import type { Schema, SchemaOptions } from './Schema'; import { BooleanSchema, NumberSchema, StringSchema } from './Schema'; +import type { SchemaWithDefaultOptions } from './Schema/SchemaOptions'; -export class Config< - TSchema extends Record, - TConfig extends Record, -> { - private value!: TConfig; +type RequiredSchema = T & { required: true }; + +export class Config> { + private value!: InferType; constructor(private schema: TSchema) {} - public parse(value: TConfig) { - this.value = value; + public parse(value: Partial>) { + this.value = value as Record; Object.entries(this.schema).forEach(([key, s]) => { s.key = key; s.setValue(this.value[key]); s.validate(); - this.value[key as keyof TConfig] = s.parse(); + this.value[key as keyof InferType] = s.parse(); }); return this; } - static string(options?: SchemaOptions) { - return new StringSchema(options); + static string>( + options?: T, + ): T extends SchemaWithDefaultOptions + ? RequiredSchema> + : StringSchema { + return new StringSchema(options) as any; + } + + static boolean>( + options?: T, + ): T extends SchemaWithDefaultOptions + ? RequiredSchema> + : BooleanSchema { + return new BooleanSchema(options) as any; } - static boolean(options?: SchemaOptions) { - return new BooleanSchema(options); + static number>( + options?: T, + ): T extends SchemaWithDefaultOptions + ? RequiredSchema> + : NumberSchema { + return new NumberSchema(options) as any; } - static number(options?: SchemaOptions) { - return new NumberSchema(options); + public get(key: TKey) { + return this.value[key] as InferType[TKey]; } public getAll(): InferType { diff --git a/src/Schema/SchemaOptions.ts b/src/Schema/SchemaOptions.ts index 573634b..2114df9 100644 --- a/src/Schema/SchemaOptions.ts +++ b/src/Schema/SchemaOptions.ts @@ -1,4 +1,13 @@ -export interface SchemaOptions { - default?: TInput; +export interface SchemaWithDefaultOptions { + default: TInput; coerce?: boolean; } + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface NullableSchemaOptions { + coerce?: boolean; +} + +export type SchemaOptions = + | NullableSchemaOptions + | SchemaWithDefaultOptions;