crenshaw-dev
crenshaw-dev

Reputation: 8354

TypeScript - how to prevent overwriting class methods with variables in constructor

I have a large code base where some class members are set twice - once as a method, and the other explicitly in the constructor.

Here is a an example of what this might look like:

class SuperHero {
    public name: string;

    constructor(name: string) {
        this.name = name;

        // This line is a problem.
        this.hasCape = () => {
            return this.name === 'Batman';
        };
    }

    // I want this to be the canonical implementation.
    public hasCape() {
        return this.name === 'Batman' || this.name === 'Wonder Woman';
    }
}

It looks like public readonly hasCape() is invalid syntax.

Is there a way to enforce the method declaration as canonical at the compiler or linter level?

Upvotes: 4

Views: 1234

Answers (1)

Chris J
Chris J

Reputation: 121

Inspired by the comment from Aaron Beall. This makes hasCape a property, that's a function, that's readonly. The typescript compiler then throws an error when assigning it from the constructor.

    public get hasCape() {
        return () => this.name === 'Batman' || this.name === 'Wonder Woman';
    }

Upvotes: 1

Related Questions