Skip to content

Commit 88dad89

Browse files
committed
Make "required" optional in TypeScript typings
1 parent 45b9708 commit 88dad89

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

index.d.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
type AnySchema = NullSchema | BooleanSchema | NumberSchema | StringSchema | AnyEnumSchema | AnyArraySchema | AnyObjectSchema
1+
type AnySchema = NullSchema | BooleanSchema | NumberSchema | StringSchema | AnyEnumSchema | AnyArraySchema | AnyObjectSchema | AnyAllOptionalObjectSchema
22
type StringKeys<T> = (keyof T) & string
33

44
interface NullSchema {
@@ -36,6 +36,13 @@ interface ObjectSchema<Properties extends Record<string, AnySchema>, Required ex
3636
required: Required[]
3737
}
3838

39+
interface AnyAllOptionalObjectSchema extends AllOptionalObjectSchema<Record<string, AnySchema>> {}
40+
interface AllOptionalObjectSchema<Properties extends Record<string, AnySchema>> {
41+
additionalProperties?: boolean
42+
type: 'object'
43+
properties: Properties
44+
}
45+
3946
interface ArrayFromSchema<ItemSchema extends AnySchema> extends Array<TypeFromSchema<ItemSchema>> {}
4047

4148
type ObjectFromSchema<Properties extends Record<string, AnySchema>, Required extends StringKeys<Properties>> = {
@@ -50,6 +57,7 @@ type TypeFromSchema<Schema extends AnySchema> = (
5057
: Schema extends StringSchema ? string
5158
: Schema extends ArraySchema<infer ItemSchema> ? ArrayFromSchema<ItemSchema>
5259
: Schema extends ObjectSchema<infer Properties, infer Required> ? ObjectFromSchema<Properties, Required>
60+
: Schema extends AllOptionalObjectSchema<infer Properties> ? ObjectFromSchema<Properties, never>
5361
: never
5462
)
5563

test/typings.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,3 +186,21 @@ if (metricValidator(input)) {
186186
assertType<'page-view'>(input.name)
187187
assertType<string>(input.page)
188188
}
189+
190+
const noRequiredFieldsValidator = createValidator({
191+
type: 'object',
192+
properties: {
193+
a: { type: 'string' },
194+
b: { type: 'string' },
195+
c: { type: 'string' }
196+
}
197+
})
198+
199+
if (noRequiredFieldsValidator(input)) {
200+
if (typeof input.a !== 'string') assertType<undefined>(input.a)
201+
if (typeof input.b !== 'string') assertType<undefined>(input.b)
202+
if (typeof input.c !== 'string') assertType<undefined>(input.c)
203+
if (typeof input.a !== 'undefined') assertType<string>(input.a)
204+
if (typeof input.b !== 'undefined') assertType<string>(input.b)
205+
if (typeof input.c !== 'undefined') assertType<string>(input.c)
206+
}

0 commit comments

Comments
 (0)