Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types: correct schema type inference when using nested typeKey like type: { type: String } #14956

Merged
merged 1 commit into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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