Skip to content

Commit 0752c5d

Browse files
authored
Merge pull request #14956 from Automattic/vkarpov15/gh-14950
types: correct schema type inference when using nested typeKey like `type: { type: String }`
2 parents ccf4ffa + c187fd8 commit 0752c5d

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

test/types/schema.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1645,3 +1645,21 @@ function gh8389() {
16451645
function gh14879() {
16461646
Schema.Types.String.setters.push((val?: unknown) => typeof val === 'string' ? val.trim() : val);
16471647
}
1648+
1649+
async function gh14950() {
1650+
const SightingSchema = new Schema(
1651+
{
1652+
_id: { type: Schema.Types.ObjectId, required: true },
1653+
location: {
1654+
type: { type: String, required: true },
1655+
coordinates: [{ type: Number }]
1656+
}
1657+
}
1658+
);
1659+
1660+
const TestModel = model('Test', SightingSchema);
1661+
const doc = await TestModel.findOne().orFail();
1662+
1663+
expectType<string>(doc.location!.type);
1664+
expectType<number[]>(doc.location!.coordinates);
1665+
}

types/inferschematype.d.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,16 @@ type TypeHint<T> = T extends { __typehint: infer U } ? U: never;
183183
* @param {TypeKey} TypeKey A generic refers to document definition.
184184
*/
185185
type ObtainDocumentPathType<PathValueType, TypeKey extends string = DefaultTypeKey> = ResolvePathType<
186-
PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? PathValueType[TypeKey] : PathValueType,
187-
PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? Omit<PathValueType, TypeKey> : {},
186+
PathValueType extends PathWithTypePropertyBaseType<TypeKey>
187+
? PathValueType[TypeKey] extends PathWithTypePropertyBaseType<TypeKey>
188+
? PathValueType
189+
: PathValueType[TypeKey]
190+
: PathValueType,
191+
PathValueType extends PathWithTypePropertyBaseType<TypeKey>
192+
? PathValueType[TypeKey] extends PathWithTypePropertyBaseType<TypeKey>
193+
? {}
194+
: Omit<PathValueType, TypeKey>
195+
: {},
188196
TypeKey,
189197
TypeHint<PathValueType>
190198
>;

0 commit comments

Comments
 (0)