Jason
Jason

Reputation: 33

Adding a public getter, private setter to a TypeScript prototype

I'm trying to add a property, let's call it "features", to the HTMLElement prototype in TypeScript. It can init as null, and it needs to be restricted to a particular class in my codebase (called FeatureManager). That's all quite easy. What I'm struggling with, and I'm not very well-versed in JS/TS, is setting up the new property so it has a public getter, but a private setter. Basically I want the setup to be that I call a new method on any given HTMLElement to setup the features object, and then that HTMLElement has the same features object for the page's lifetime, I don't want it to be overridden except maybe by an internal HTMLElement method. How do I set this up?

So normally it's easy, like:

class HTMLElementPlus {
    private _features: FeatureManager;

    public get features() {
        return this._features;
    }

    private set features(features: FeatureManager) {
        this._features = features;
    }
}

But the issue I'm having is how do I get the same public getter, private setter for an extension onto an existing prototype?

So I can easily add:

interface HTMLElement {
    features: FeatureManager;
}

But how do I apply a private setter to this within the prototype?

Upvotes: 2

Views: 768

Answers (1)

Ronald C
Ronald C

Reputation: 357

You can create an interface with only the getter:

interface HTMLElement {
    get features(): any
}

const a = {} as HTMLElement

a.features = 42 // Cannot assign to 'features' because it is a read-only property.(2540)
const b = a.features // No error

Hope that works for you.

Upvotes: 0

Related Questions