I am looking to create a function that can reference the current object's type in its parameter and return types, like so:
inside .d.ts
:
interface Object {
add(object: Partial<this>): this;
}
within .js
:
Object.prototype.add = function(object) {
Object.assign(this, object);
}
The purpose of this function is to only accept properties for the parameter that are already defined on the object using Partial<this>
. However, when attempting to use it like this:
document.body.style.add({
fontSize: "12px"
});
TypeScript throws an error:
Argument of type '{ fontSize: string; }' is not assignable to parameter of type `Partial<Object>`.
Object literal may only specify known properties, and 'fontSize' does not exist in type 'Partial<Object>'.
I believe this issue arises because the this
in my .d.ts
refers to Object
and not recognizing the proper type such as CSSStyleDeclaration
for document.body.style
. How can I achieve a function like this, which utilizes the object's type for parameters/return types? Is this attainable in TypeScript?