I have an interface that looks like this:
export interface Attribute {
name: string;
}
With this I can use this syntax to create an Attribute:
const attr: Attribute = {
name: "foo"
};
My problem is that I don't want to use classes because they are clumsy and not flexible enough, but I want to keep using the syntax above for creating objects because it is very succinct. I've read that it is possible to do declaration merging so I tried to do this to add a new function to this interface:
import { Attribute } from "./Attribute";
declare module "./Attribute" {
interface Attribute {
matches(other: Attribute): boolean;
}
}
Attribute.prototype.matches = function (other: Attribute): boolean {
return this.name === other.name;
};
The problem here is that there is no prototype to augment since interfaces are not available at runtime. If I merge the Attribute interface with a class:
export class Attribute {}
export interface Attribute {
name: string;
}
there is a prototype and the augmentation compiles but I still can't use it:
import { Attribute } from "./Attribute";
import "./AttributeAugments";
const attr: Attribute = {
name: "foo"
};
// ^^^--- Property 'matches' is missing in type '{ id: number; name: string; }' but required in type 'Attribute'
console.log(attr);
Is there a way to somehow do this? What I'm aiming for is to be able to do attr.matches(other) instead of having to do matches(attr, other). This way I could do function chaining like attr.a().b().c() instead of having to do c(b(a(attr))).
attr?