Skip to content

Commit

Permalink
types: correct schema type inference when using nested typeKey like `…
Browse files Browse the repository at this point in the history
…type: { type: String }`

Fix #14950
  • Loading branch information
vkarpov15 committed Oct 11, 2024
1 parent 02c5efd commit c187fd8
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 c187fd8

Please sign in to comment.