Drenai
Drenai

Reputation: 12347

TSLint ESLint - warn when function accessed as property?

I have made this mistake a few times - and want to know if there's an ESLint or TSLint rule that would spot it

if (this.isBrowser && this.imageURL) {.....}

private isBrowser(): boolean{
    return isPlatformBrowser(this.platformId);
}

Using this.isBrowser will always return true, as the fact it's a function is truthy. I either have to use get isBrowser() {} or this.isBrowser()

Can ESLint or TSLint check and warn that a call to a function is being written as a property accessor?

Upvotes: 2

Views: 761

Answers (1)

Estus Flask
Estus Flask

Reputation: 222319

The only case when property getters can be handled by linters is when they are potentially no-op, there is TSLint/ESLint no-unused-expression rule:

this.isBrowser; // causes linter error

This is the case with Chai assertions. In any other case this.isBrowser is not a no-op.

if (this.isBrowser) is valid piece of code that checks that isBrowser member is truthy. It could be valid for a method, if (this.isBrowser) this.isBrowser().

A way to solve this problem with TypeScript is to not be lazy about conditions

if (this.isBrowser === true && this.imageURL) {.....}

This will result in type error if isBrowser is a function.

This is a problem that potentially results from indeterminate code style. If a method that checks if it is a browser is called isBrowser, how would boolean property be called then? The fact that a method and a property can be confused and cannot coexist suggests that a a method that returns a boolean may have a distinct name, e.g. getIsBrowser, while isBrowser is reserved for boolean value.

Upvotes: 2

Related Questions