Closed
Description
TypeScript Version: 4.1.2 and 4.2.0-dev.20201123
Search Terms: UpdateQuery
, Intersection
, Generic
Code
import { UpdateQuery } from 'mongodb';
interface Foo {
foo: string;
}
function testWithGeneric<TSchema>(): UpdateQuery<TSchema> {
const update: UpdateQuery<TSchema> = {};
if (Math.random() < 0.5) {
const key: string = 'newKey';
const value: any = true;
update.$set = {
...(update.$set || {}),
[key]: value
};
}
return update;
}
function testWithoutGeneric(): UpdateQuery<Foo> {
const update: UpdateQuery<Foo> = {};
if (Math.random() < 0.5) {
const key: string = 'newKey';
const value: any = true;
update.$set = {
...(update.$set || {}),
[key]: value
};
}
return update;
}
Where the UpdateQuery
definition in the mongodb
types is defined as:
type DotAndArrayNotation<AssignableType> = {
readonly [key: string]: AssignableType;
};
type ReadonlyPartial<TSchema> = {
readonly [key in keyof TSchema]?: TSchema[key];
};
export type MatchKeysAndValues<TSchema> = ReadonlyPartial<TSchema> & DotAndArrayNotation<any>;
export type UpdateQuery<TSchema> = {
$set?: MatchKeysAndValues<TSchema>;
// other fields here don't matter
};
Expected behavior:
Code is valid.
Actual behavior:
Only the function testWithGeneric
throws an error. But since MatchKeysAndValues
is defined as an intersection between ReadonlyPartial<TSchema>
and a mapped type of string keys with any values, it should be accepted.
Type '{ [x: string]: any; }' is not assignable to type 'MatchKeysAndValues<TSchema>'. Type '{ [x: string]: any; }' is not assignable to type 'ReadonlyPartial<TSchema>'.
This used to work in version 4.0.5.