Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

New Rule: param-property-in-constructor #1358

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ Core rules are included in the `tslint` package.
* `one-variable-per-declaration` disallows multiple variable definitions in the same statement.
* `"ignore-for-loop"` allows multiple variable definitions in for loop statement.
* `only-arrow-functions` disallows traditional `function () { ... }` declarations, preferring `() => { ... }` arrow lambdas.
* `param-property-in-constructor` Disallows `private`, `public`, or `protected` constructor parameter properties to be accessed without the `this.` prefix.
* `quotemark` enforces consistent single or double quoted string literals. Rule options (at least one of `"double"` or `"single"` is required):
* `"single"` enforces single quotes.
* `"double"` enforces double quotes.
Expand Down
96 changes: 96 additions & 0 deletions src/rules/paramPropertyInConstructorRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* @license
* Copyright 2014 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as Lint from "../lint";
import * as ts from "typescript";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "param-property-in-constructor",
description: "Disallows constructor parameter properties to be accessed without the 'this.' prefix",
rationale: Lint.Utils.dedent`
This helps enforce consistancy.
When a constructor parameter is accessed without the 'this.' prefix, it is actually not acessing the same thing.
Example:
class Foo {
constructor(public num: number) {
this.num = 10;
num = 5; //this should be disallowed!
}
}
const f = new Foo();
alert(f.num); // will display 10`,
optionsDescription: "Not configurable.",
options: null,
optionExamples: ["true"],
type: "functionality",
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_STRING_FACTORY = (paramName: string) => {
return `The constructor parameter '${paramName}' should only be accessed with the 'this' keyword: 'this.${paramName}'`;
}

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const languageService = Lint.createLanguageService(sourceFile.fileName, sourceFile.getFullText());
return this.applyWithWalker(new ParamPropInCtorWalker(sourceFile, this.getOptions(), languageService));
}
}

export class ParamPropInCtorWalker extends Lint.RuleWalker {

constructor(sourceFile: ts.SourceFile, options: Lint.IOptions, private languageService: ts.LanguageService) {
super(sourceFile, options);
this.languageService = languageService;
}

public visitConstructorDeclaration(node: ts.ConstructorDeclaration) {
if (node.parameters && node.parameters.length > 0) {
const fileName = this.getSourceFile().fileName;
for (let param of node.parameters) {
if (param.modifiers != null && param.modifiers.length > 0) {
this.validateParam(param, fileName);
}
}
}
super.visitConstructorDeclaration(node);
}

private validateParam(param: ts.ParameterDeclaration, fileName: string) {
const highlights = this.languageService.getDocumentHighlights(fileName, param.name.getStart(), [fileName]);

if ((highlights !== null && highlights[0].highlightSpans.length > 0)) {
const paramName = param.name.getText();
highlights[0].highlightSpans.forEach((span: ts.HighlightSpan, idx: number) => {
// Ignore the 1st reference which is the actual parameter definition
if (idx !== 0 && !this.spanHasThisUsage(span, fileName)) {
const msg = Rule.FAILURE_STRING_FACTORY(paramName);
this.addFailure(this.createFailure(span.textSpan.start, span.textSpan.length, msg));
}
});
}
}

private spanHasThisUsage(span: ts.HighlightSpan, fileName: string) {
const endPos = span.textSpan.start + span.textSpan.length;
const nameSpanInfo = this.languageService.getNameOrDottedNameSpan(fileName, span.textSpan.start, endPos);

// If the difference between these two is exactly 5 characters it accounts for the missing `this.`!
return nameSpanInfo.length - span.textSpan.length === 5;
}
}
1 change: 1 addition & 0 deletions src/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@
"rules/oneVariablePerDeclarationRule.ts",
"rules/onlyArrowFunctionsRule.ts",
"rules/orderedImportsRule.ts",
"rules/paramPropertyInConstructorRule.ts",
"rules/quotemarkRule.ts",
"rules/radixRule.ts",
"rules/restrictPlusOperandsRule.ts",
Expand Down
65 changes: 65 additions & 0 deletions test/rules/param-property-in-constructor/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
class FailingExample1 {
constructor(fruit: string, public num: number, private animal: string, protected mineral: string) {
//Both usage here are OK since `fruit` is a regular parameter and not a class property
fruit = "banana";
this.fruit = "persimmon";

this.num = 10;
num = 5;
~~~ [The constructor parameter 'num' should only be accessed with the 'this' keyword: 'this.num']

animal = "aardvark";
~~~~~~ [The constructor parameter 'animal' should only be accessed with the 'this' keyword: 'this.animal']
this.animal = "skunk";

mineral = "Gypsum";
~~~~~~~ [The constructor parameter 'mineral' should only be accessed with the 'this' keyword: 'this.mineral']
this.mineral = "Fluorite";
}
}

class FailingExample2 {
constructor(public thing: Object) {
const wow=thing.doTheThing()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I wasn't thinking about this use case. When accessing a value, it doesn't matter if you use this. or not. Do you think we should still disallow this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the other hand, using this. doesn't hurt

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah that was my thinking with the way it was written initially. I was thinking that if we just require this. on everything, then there is consistency for how all constructor params are used, regardless if they are used as properties or not.

~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing']
console.log(wow, thing.amazingDvdCollection);
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing']

const pasta = thing.nested.makePasta();
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing']

thing = {};
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing']

this.thing.doSomethingElse();
}
}

class PassingExample1 {
//This is OK since `thing` is a regular parameter and not a class property here
constructor(thing: Object) {
const wow=thing.doTheThing()
console.log(wow,thing.amazingDvdCollection);
const pasta = thing.nested.makePasta();
thing = {};
this.thing.doSomethingElse();
}
}

class PassingExample2 {
constructor(a: string, private b: string, public c: string, protected d: string) {
this.a = "aaa";
this.b = "bbb";
this.c = "ccc";
this.d = "ddd";
}
}

class PassingExample3 {
constructor(a: Object, private b: Object, public c: Object, protected d: Object) {
this.a.doThing();
this.b.doOtherThing();
this.c.doAnotherThing();
this.d.doLastThing();
}
}
5 changes: 5 additions & 0 deletions test/rules/param-property-in-constructor/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"param-property-in-constructor": true
}
}
1 change: 1 addition & 0 deletions test/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@
"../src/rules/oneVariablePerDeclarationRule.ts",
"../src/rules/onlyArrowFunctionsRule.ts",
"../src/rules/orderedImportsRule.ts",
"../src/rules/paramPropertyInConstructorRule.ts",
"../src/rules/quotemarkRule.ts",
"../src/rules/radixRule.ts",
"../src/rules/restrictPlusOperandsRule.ts",
Expand Down