When using the code snippet below and not explicitly specifying T
at function call, such as getOrPut<Item>(...)
, it is inferred from the create
parameter. However, this can lead to the created item type being incompatible with the obj
dictionary, as shown in the last line of the code.
function getOrPut<T>(
obj: { [key: string]: T | undefined },
key: string,
create: () => T
): T {
const value = obj[key];
if (value) {
return value;
} else {
return obj[key] = create();
}
};
type Item = { title: string };
type Dictionary = { [key: string]: Item };
const dictionary: Dictionary = {};
// The type of `foo` is {} but an `Item` is expected
const foo = getOrPut(dictionary, 'foo', () => ({}));
Is there a way to enforce the inference of T
from the obj
parameter?