I created a function called `hasOwnProperty` with type narrowing:
function hasOwnProperty<
Obj extends Record<string, any>,
Prop extends PropertyKey,
>(
obj: Obj,
prop: Prop,
): obj is Obj & Record<Prop, any> {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
I thought a simple function like this would work:
function addProp<T>(obj: Record<string, any>, key: string, val: any) {
if (!hasOwnProperty(obj, key)) {
obj[key] = val;
}
}
However, I'm getting an error message saying
Type 'any' is not assignable to type 'never'.
This seems logical because the type narrowing indicates that `key` does not exist in the `obj`. However, it should not prevent me from adding the key. Am I missing something?
Edit: Moreover, the same issue occurs outside of a function as well:
const obj: Record<string, number> = {};
const key = 'key';
if (!hasOwnProperty(obj, key)) {
obj[key] = 123;
}