Saturday, 26 June 2021

Override types for built-in methods on prototype

The default type for hasOwnProperty is hasOwnProperty(v: PropertyKey): boolean;. However, this prevents me from doing things like:

const obj = { a: 1 };

function foo(str: string) {
    if (obj.hasOwnProperty(str)) {
        console.log(obj[str]);
        // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; }'.
    }
}

To override the type for obj.hasOwnProperty, I added:

interface Object {
  hasOwnProperty<T extends ObjectOf<any>>(this: T, key: any): key is keyof T;
}

This works for obj.hasOwnProperty(key), but not Object.prototype.hasOwnProperty.call(obj, key). How can I override hasOwnProperty's type when I call it using the second method?

Edit: to clarify, even with the override, the following doesn't work:

const obj = { a: 1 };

function foo(str: string) {
    if (Object.prototype.hasOwnProperty.call(obj, str)) {
        console.log(obj[str]);
        // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; }'.
    }
}


from Override types for built-in methods on prototype

No comments:

Post a Comment