Skip to content

Commit

Permalink
Create InferDocType utility.
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammad0-0ahmad committed Jun 8, 2022
1 parent 1b21255 commit ea16fd9
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
6 changes: 5 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, InferSchemaType, SchemaType, Query, HydratedDocument } from 'mongoose';
import { Schema, Document, SchemaDefinition, Model, Types, InferSchemaType, SchemaType, Query, HydratedDocument, InferDocType, FlatRecord } from 'mongoose';
import { expectType, expectError, expectAssignable } from 'tsd';

enum Genre {
Expand Down Expand Up @@ -507,6 +507,10 @@ export function autoTypedSchema() {

expectError<AutoTypedSchemaType['schema'] & { doesNotExist: boolean; }>({} as InferredSchemaType);

type InferredDocType = InferDocType<typeof AutoTypedSchema>;

expectType<FlatRecord<AutoTypedSchemaType['schema'] & AutoTypedSchemaType['virtuals']>>({} as InferredDocType);

return AutoTypedSchema;
}

Expand Down
14 changes: 13 additions & 1 deletion types/inferschematype.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,19 @@ declare module 'mongoose' {
* // result
* type UserType = {userName?: string}
*/
type InferSchemaType<SchemaType> = ObtainSchemaGeneric<SchemaType, 'DocType'> ;
type InferSchemaType<SchemaType> = ObtainSchemaGeneric<SchemaType, 'DocType'>;

/**
* @summary Obtains document plain doc type from Schema instance.
* @description Exactly like {@link InferSchemaType}, but it add virtual paths.
* @param {SchemaType} SchemaType A generic of schema type instance.
* @example
* const userSchema = new Schema({userName:String});
* type UserType = InferDocType<typeof userSchema>;
* // result
* type UserType = {userName?: string}
*/
type InferDocType<SchemaType> = FlatRecord<InferSchemaType<SchemaType> & ObtainSchemaGeneric<SchemaType, 'TVirtuals'>>;

/**
* @summary Obtains schema Generic type by using generic alias.
Expand Down
8 changes: 8 additions & 0 deletions types/utility.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,12 @@ type IfEquals<T, U, Y = true, N = false> =
(<G>() => G extends T ? 1 : 0) extends
(<G>() => G extends U ? 1 : 0) ? Y : N;


/**
* @summary Converts Unions to one record "object".
* @description It makes intellisense dialog box easier to read as a single object instead of showing that in multiple object unions.
* @param {T} T The type to be converted.
*/
type FlatRecord<T> = { [K in keyof T]: T[K] };

}

0 comments on commit ea16fd9

Please sign in to comment.