Skip to content

Commit

Permalink
Merge pull request #12463 from Automattic/vkarpov15/gh-12242
Browse files Browse the repository at this point in the history
fix(types): infer number enum types from schema if using `enum: [0, 1] as const`
  • Loading branch information
vkarpov15 committed Sep 22, 2022
2 parents 69c99d2 + bb06027 commit 6153970
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
11 changes: 11 additions & 0 deletions test/types/schema.test.ts
Expand Up @@ -741,3 +741,14 @@ function pluginOptions() {
schema.plugin<any, SomePluginOptions>(pluginFunction2, { option2: 0 });
expectError(schema.plugin<any, SomePluginOptions>(pluginFunction2, {})); // should error because "option2" is not optional
}

function gh12242() {
const dbExample = new Schema(
{
active: { type: Number, enum: [0, 1] as const, required: true }
}
);

type Example = InferSchemaType<typeof dbExample>;
expectType<0 | 1>({} as Example['active']);
}
2 changes: 1 addition & 1 deletion types/inferschematype.d.ts
Expand Up @@ -156,7 +156,7 @@ type ResolvePathType<PathValueType, Options extends SchemaTypeOptions<PathValueT
PathValueType extends Schema ? InferSchemaType<PathValueType> :
PathValueType extends (infer Item)[] ? IfEquals<Item, never, any[], Item extends Schema ? Types.DocumentArray<ResolvePathType<Item>> : ResolvePathType<Item>[]> :
PathValueType extends StringSchemaDefinition ? PathEnumOrString<Options['enum']> :
PathValueType extends NumberSchemaDefinition ? number :
PathValueType extends NumberSchemaDefinition ? Options['enum'] extends ReadonlyArray<any> ? Options['enum'][number] : number :
PathValueType extends DateSchemaDefinition ? Date :
PathValueType extends typeof Buffer | 'buffer' | 'Buffer' | typeof Schema.Types.Buffer ? Buffer :
PathValueType extends BooleanSchemaDefinition ? boolean :
Expand Down

0 comments on commit 6153970

Please sign in to comment.