Skip to content

Commit

Permalink
Merge pull request #14956 from Automattic/vkarpov15/gh-14950
Browse files Browse the repository at this point in the history
types: correct schema type inference when using nested typeKey like `type: { type: String }`
  • Loading branch information
vkarpov15 authored Oct 14, 2024
2 parents ccf4ffa + c187fd8 commit 0752c5d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
18 changes: 18 additions & 0 deletions test/types/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1645,3 +1645,21 @@ function gh8389() {
function gh14879() {
Schema.Types.String.setters.push((val?: unknown) => typeof val === 'string' ? val.trim() : val);
}

async function gh14950() {
const SightingSchema = new Schema(
{
_id: { type: Schema.Types.ObjectId, required: true },
location: {
type: { type: String, required: true },
coordinates: [{ type: Number }]
}
}
);

const TestModel = model('Test', SightingSchema);
const doc = await TestModel.findOne().orFail();

expectType<string>(doc.location!.type);
expectType<number[]>(doc.location!.coordinates);
}
12 changes: 10 additions & 2 deletions types/inferschematype.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,16 @@ type TypeHint<T> = T extends { __typehint: infer U } ? U: never;
* @param {TypeKey} TypeKey A generic refers to document definition.
*/
type ObtainDocumentPathType<PathValueType, TypeKey extends string = DefaultTypeKey> = ResolvePathType<
PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? PathValueType[TypeKey] : PathValueType,
PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? Omit<PathValueType, TypeKey> : {},
PathValueType extends PathWithTypePropertyBaseType<TypeKey>
? PathValueType[TypeKey] extends PathWithTypePropertyBaseType<TypeKey>
? PathValueType
: PathValueType[TypeKey]
: PathValueType,
PathValueType extends PathWithTypePropertyBaseType<TypeKey>
? PathValueType[TypeKey] extends PathWithTypePropertyBaseType<TypeKey>
? {}
: Omit<PathValueType, TypeKey>
: {},
TypeKey,
TypeHint<PathValueType>
>;
Expand Down

0 comments on commit 0752c5d

Please sign in to comment.