Skip to content

Commit

Permalink
fix(types): make array paths optional in inferred type of array defau…
Browse files Browse the repository at this point in the history
…lt returns undefined

Fix #12420
  • Loading branch information
vkarpov15 committed Nov 2, 2022
1 parent fd2d826 commit 80f597f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
12 changes: 12 additions & 0 deletions test/types/schema.test.ts
Expand Up @@ -870,3 +870,15 @@ function gh12431() {
type Example = InferSchemaType<typeof testSchema>;
expectType<{ testDate?: Date, testDecimal?: Types.Decimal128 }>({} as Example);
}

function gh12420() {
const TestSchema = new Schema(
{
comments: { type: [String], default: () => undefined }
}
);

expectType<{
comments?: string[]
}>({} as InferSchemaType<typeof TestSchema>);
}
8 changes: 7 additions & 1 deletion types/inferschematype.d.ts
Expand Up @@ -60,6 +60,12 @@ declare module 'mongoose' {
: unknown;
}

type IsPathDefaultUndefined<PathType> = PathType extends { default: undefined } ?
true :
PathType extends { default: (...args: any[]) => undefined } ?
true :
false;

/**
* @summary Checks if a document path is required or optional.
* @param {P} P Document path.
Expand All @@ -69,7 +75,7 @@ type IsPathRequired<P, TypeKey extends TypeKeyBaseType = DefaultTypeKey> =
P extends { required: true | [true, string | undefined] } | ArrayConstructor | any[]
? true
: P extends (Record<TypeKey, ArrayConstructor | any[]>)
? P extends { default: undefined }
? IsPathDefaultUndefined<P> extends true
? false
: true
: P extends (Record<TypeKey, any>)
Expand Down

0 comments on commit 80f597f

Please sign in to comment.