I defined 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 expected a straightforward function like this to work:
function addProp<T>(obj: Record<string, any>, key: string, val: any) {
if (!hasOwnProperty(obj, key)) {
obj[key] = val;
}
}
However, I'm getting Type 'any' is not assignable to type 'never'.
This kind of makes sense because the type narrowing is saying that key
doesn't exist in obj
. However, this shouldn't prevent me from adding the key. Is there something I'm doing wrong?
Edit: Also, it doesn't work outside of a function either:
const obj: Record<string, number> = {};
const key = 'key';
if (!hasOwnProperty(obj, key)) {
obj[key] = 123;
}
from Typescript can't assign value to object key with hasOwnProperty type narrowing
No comments:
Post a Comment