Skip to content

Commit

Permalink
fix(types): handle boolean default functions
Browse files Browse the repository at this point in the history
Fix #11828
  • Loading branch information
vkarpov15 committed Jun 11, 2022
1 parent 5f39d05 commit 67eddb9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
31 changes: 30 additions & 1 deletion test/types/schema.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Schema, Document, SchemaDefinition, Model, Types } from 'mongoose';
import { Schema, Document, SchemaDefinition, SchemaDefinitionProperty, SchemaTypeOptions, Model, Types } from 'mongoose';
import { expectType, expectError } from 'tsd';

enum Genre {
Expand Down Expand Up @@ -326,3 +326,32 @@ const batchSchema = new Schema<{ name: string }>({ name: String }, { discriminat
const discriminatedSchema = batchSchema.discriminator('event', eventSchema);

expectType<Schema<Omit<{ name: string }, 'message'> & { message: string }>>(discriminatedSchema);

function gh11828() {
interface IUser {
name: string;
age: number;
bornAt: Date;
isActive: boolean;
}

const t: SchemaTypeOptions<boolean> = {
type: Boolean,
default() {
return this.name === 'Hafez';
}
};

new Schema<IUser>({
name: { type: String, default: () => 'Hafez' },
age: { type: Number, default: () => 27 },
bornAt: { type: Date, default: () => new Date() },
isActive: {
type: Boolean,
default(): boolean {
return this.name === 'Hafez';
}
}
});

}
4 changes: 3 additions & 1 deletion types/schematypes.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ declare module 'mongoose' {
/** The various Mongoose SchemaTypes. */
const SchemaTypes: typeof Schema.Types;

type DefaultType<T> = T extends Schema.Types.Mixed ? any : Partial<ExtractMongooseArray<T>>;

class SchemaTypeOptions<T> {
type?:
T extends string ? StringSchemaDefinition :
Expand Down Expand Up @@ -74,7 +76,7 @@ declare module 'mongoose' {
* The default value for this path. If a function, Mongoose executes the function
* and uses the return value as the default.
*/
default?: T extends Schema.Types.Mixed ? ({} | ((this: any, doc: any) => any)) : (ExtractMongooseArray<T> | ((this: any, doc: any) => Partial<ExtractMongooseArray<T>>));
default?: DefaultType<T> | ((this: any, doc: any) => DefaultType<T>) | null;

/**
* The model that `populate()` should use if populating this path.
Expand Down

0 comments on commit 67eddb9

Please sign in to comment.