UNPKG

23.7 kBMarkdownView Raw
1# tslint-immutable
2
3[![npm version][version-image]][version-url]
4[![travis build][travis-image]][travis-url]
5[![Coverage Status][codecov-image]][codecov-url]
6[![code style: prettier][prettier-image]][prettier-url]
7[![MIT license][license-image]][license-url]
8
9[TSLint](https://palantir.github.io/tslint/) rules to disable mutation in TypeScript.
10
11## Background
12
13In some applications it is important to not mutate any data, for example when using Redux to store state in a React application. Moreover immutable data structures has a lot of advantages in general so I want to use them everywhere in my applications.
14
15I originally used [immutablejs](https://github.com/facebook/immutable-js/) for this purpose. It is a really nice library but I found it had some drawbacks. Specifically when debugging it was hard to see the structure, creating JSON was not straightforward, and passing parameters to other libraries required converting to regular mutable arrays and objects. The [seamless-immutable](https://github.com/rtfeldman/seamless-immutable) project seems to have the same conclusions and they use regular objects and arrays and check for immutability at run-time. This solves all the aformentioned drawbacks but introduces a new drawback of only being enforced at run-time. (Altough you loose the structural sharing feature of immutablejs with this solution so you would have to consider if that is something you need).
16
17Then typescript 2.0 came along and introduced [readonly](https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#read-only-properties-and-index-signatures) options for properties, indexers and arrays. This enables us to use regular object and arrays and have the immutability enfored at compile time instead of run-time. Now the only drawback is that there is nothing enforcing the use of readonly in typescript.
18
19This can be solved by using linting rules. So the aim of this project is to leverage the type system in typescript to enforce immutability at compile-time while still using regular objects and arrays.
20
21## Installing
22
23`npm install tslint-immutable --save-dev`
24
25See the [example](#sample-configuration-file) tslint.json file for configuration.
26
27## Compability
28
29* tslint-immutable 5.x.x requires typescript >=2.8, node >=6, and tslint 5.x.x.
30* tslint-immutable 3.x.x requires tslint 5.x.x.
31* tslint-immutable 2.x.x requires tslint 4.x.x.
32* tslint-immutable 1.x.x requires tslint 3.x.x.
33
34## TSLint Rules
35
36In addition to immutable rules this project also contains a few rules for enforcing a functional style of programming. The following rules are available:
37
38* [Immutability rules](#immutability-rules)
39 * [readonly-keyword](#readonly-keyword)
40 * [readonly-array](#readonly-array)
41 * [no-let](#no-let)
42 * [no-array-mutation](#no-array-mutation)
43 * [no-object-mutation](#no-object-mutation)
44 * [no-method-signature](#no-method-signature)
45 * [no-delete](#no-delete)
46* [Functional style rules](#functional-style-rules)
47 * [no-this](#no-this-no-class)
48 * [no-class](#no-this-no-class)
49 * [no-mixed-interface](#no-mixed-interface)
50 * [no-expression-statement](#no-expression-statement)
51 * [no-if-statement](#no-if-statement)
52 * [no-loop-statement](#no-loop-statement)
53 * [no-throw](#no-throw)
54 * [no-try](#no-try)
55* [Recommended built-in rules](#recommended-built-in-rules)
56
57## Immutability rules
58
59### readonly-keyword
60
61This rule enforces use of the `readonly` modifier. The `readonly` modifier can appear on property signatures in interfaces, property declarations in classes, and index signatures.
62
63Below is some information about the `readonly` modifier and the benefits of using it:
64
65You might think that using `const` would eliminate mutation from your TypeScript code. **Wrong.** Turns out that there's a pretty big loophole in `const`.
66
67```typescript
68interface Point {
69 x: number;
70 y: number;
71}
72const point: Point = { x: 23, y: 44 };
73point.x = 99; // This is legal
74```
75
76This is why the `readonly` modifier exists. It prevents you from assigning a value to the result of a member expression.
77
78```typescript
79interface Point {
80 readonly x: number;
81 readonly y: number;
82}
83const point: Point = { x: 23, y: 44 };
84point.x = 99; // <- No object mutation allowed.
85```
86
87This is just as effective as using Object.freeze() to prevent mutations in your Redux reducers. However the `readonly` modifier has **no run-time cost**, and is enforced at **compile time**. A good alternative to object mutation is to use the ES2016 object spread [syntax](https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#object-spread-and-rest) that was added in typescript 2.1:
88
89```typescript
90interface Point {
91 readonly x: number;
92 readonly y: number;
93}
94const point: Point = { x: 23, y: 44 };
95const transformedPoint = { ...point, x: 99 };
96```
97
98Note that you can also use object spread when destructuring to [delete keys](http://stackoverflow.com/questions/35342355/remove-data-from-nested-objects-without-mutating/35676025#35676025) in an object:
99
100```typescript
101let { [action.id]: deletedItem, ...rest } = state;
102```
103
104The `readonly` modifier also works on indexers:
105
106```typescript
107const foo: { readonly [key: string]: number } = { a: 1, b: 2 };
108foo["a"] = 3; // Error: Index signature only permits reading
109```
110
111#### Has Fixer
112
113Yes
114
115#### Options
116
117* [ignore-local](#using-the-ignore-local-option)
118* [ignore-class](#using-the-ignore-class-option)
119* [ignore-interface](#using-the-ignore-interface-option)
120* [ignore-prefix](#using-the-ignore-prefix-option)
121
122#### Example config
123
124```javascript
125"readonly-keyword": true
126```
127
128```javascript
129"readonly-keyword": [true, "ignore-local"]
130```
131
132```javascript
133"readonly-keyword": [true, "ignore-local", {"ignore-prefix": "mutable"}]
134```
135
136### readonly-array
137
138This rule enforces use of `ReadonlyArray<T>` instead of `Array<T>` or `T[]`.
139
140Below is some information about the `ReadonlyArray<T>` type and the benefits of using it:
141
142Even if an array is declared with `const` it is still possible to mutate the contents of the array.
143
144```typescript
145interface Point {
146 readonly x: number;
147 readonly y: number;
148}
149const points: Array<Point> = [{ x: 23, y: 44 }];
150points.push({ x: 1, y: 2 }); // This is legal
151```
152
153Using the `ReadonlyArray<T>` type will stop this mutation:
154
155```typescript
156interface Point {
157 readonly x: number;
158 readonly y: number;
159}
160const points: ReadonlyArray<Point> = [{ x: 23, y: 44 }];
161points.push({ x: 1, y: 2 }); // Unresolved method push()
162```
163
164#### Has Fixer
165
166Yes
167
168#### Options
169
170* [ignore-local](#using-the-ignore-local-option)
171* [ignore-prefix](#using-the-ignore-prefix-option)
172* [ignore-return-type](#using-the-ignore-return-type-option)
173* [ignore-rest-parameters](#using-the-ignore-rest-parameters-option)
174
175#### Example config
176
177```javascript
178"readonly-array": true
179```
180
181```javascript
182"readonly-array": [true, "ignore-local"]
183```
184
185```javascript
186"readonly-array": [true, "ignore-local", {"ignore-prefix": "mutable"}]
187```
188
189### no-let
190
191This rule should be combined with tslint's built-in `no-var-keyword` rule to enforce that all variables are declared as `const`.
192
193There's no reason to use `let` in a Redux/React application, because all your state is managed by either Redux or React. Use `const` instead, and avoid state bugs altogether.
194
195```typescript
196let x = 5; // <- Unexpected let or var, use const.
197```
198
199What about `for` loops? Loops can be replaced with the Array methods like `map`, `filter`, and so on. If you find the built-in JS Array methods lacking, use [ramda](http://ramdajs.com/), or [lodash-fp](https://github.com/lodash/lodash/wiki/FP-Guide).
200
201```typescript
202const SearchResults = ({ results }) => (
203 <ul>
204 {results.map(result => <li>result</li>) // <- Who needs let?
205 }
206 </ul>
207);
208```
209
210#### Has Fixer
211
212Yes
213
214#### Options
215
216* [ignore-local](#using-the-ignore-local-option)
217* [ignore-prefix](#using-the-ignore-prefix-option)
218
219#### Example config
220
221```javascript
222"no-let": true
223```
224
225```javascript
226"no-let": [true, "ignore-local"]
227```
228
229```javascript
230"no-let": [true, "ignore-local", {"ignore-prefix": "mutable"}]
231```
232
233### no-array-mutation
234
235[![Type Info Required][type-info-badge]][type-info-url]
236
237This rule prohibits mutating an array via assignment to or deletion of their elements/properties. This rule enforces array immutability without the use of `ReadonlyArray<T>` (as apposed to [readonly-array](#readonly-array)).
238
239```typescript
240const x = [0, 1, 2];
241
242x[0] = 4; // <- Mutating an array is not allowed.
243x.length = 1; // <- Mutating an array is not allowed.
244x.push(3); // <- Mutating an array is not allowed.
245```
246
247#### Has Fixer
248
249No
250
251#### Options
252
253* [ignore-prefix](#using-the-ignore-prefix-option)
254* [ignore-new-array](#using-the-ignore-new-array-option-with-no-array-mutation)
255* ~~ignore-mutation-following-accessor~~ - *deprecated in favor of [ignore-new-array](#using-the-ignore-new-array-option-with-no-array-mutation)*
256
257#### Example config
258
259```javascript
260"no-array-mutation": true
261```
262
263```javascript
264"no-array-mutation": [true, {"ignore-prefix": "mutable"}]
265```
266
267```javascript
268"no-array-mutation": [true, "ignore-new-array"]
269```
270
271### no-object-mutation
272
273This rule prohibits syntax that mutates existing objects via assignment to or deletion of their properties. While requiring the `readonly` modifier forces declared types to be immutable, it won't stop assignment into or modification of untyped objects or external types declared under different rules. Forbidding forms like `a.b = 'c'` is one way to plug this hole. Inspired by the no-mutation rule of [eslint-plugin-immutable](https://github.com/jhusain/eslint-plugin-immutable).
274
275```typescript
276const x = { a: 1 };
277
278x.foo = "bar"; // <- Modifying properties of existing object not allowed.
279x.a += 1; // <- Modifying properties of existing object not allowed.
280delete x.a; // <- Modifying properties of existing object not allowed.
281```
282
283#### Has Fixer
284
285No
286
287#### Options
288
289* [ignore-prefix](#using-the-ignore-prefix-option)
290
291#### Example config
292
293```javascript
294"no-object-mutation": true
295```
296
297```javascript
298"no-object-mutation": [true, {"ignore-prefix": "mutable"}]
299```
300
301### no-method-signature
302
303There are two ways function members can be declared in an interface or type alias:
304
305```typescript
306interface Zoo {
307 foo(): string; // MethodSignature, cannot have readonly modifier
308 readonly bar: () => string; // PropertySignature
309}
310```
311
312The `MethodSignature` and the `PropertySignature` forms seem equivalent, but only the `PropertySignature` form can have a `readonly` modifier. Becuase of this any `MethodSignature` will be mutable. Therefore the `no-method-signature` rule disallows usage of this form and instead proposes to use the `PropertySignature` which can have a `readonly` modifier. It should be noted however that the `PropertySignature` form for declaring functions does not support overloading.
313
314### no-delete
315
316The delete operator allows for mutating objects by deleting keys. This rule disallows any delete expressions.
317
318```typescript
319delete object.property; // Unexpected delete, objects should be considered immutable.
320```
321
322As an alternative the spread operator can be used to delete a key in an object (as noted [here](https://stackoverflow.com/a/35676025/2761797)):
323
324```typescript
325const { [action.id]: deletedItem, ...rest } = state;
326```
327
328## Functional style rules
329
330### no-this, no-class
331
332Thanks to libraries like [recompose](https://github.com/acdlite/recompose) and Redux's [React Container components](http://redux.js.org/docs/basics/UsageWithReact.html), there's not much reason to build Components using `React.createClass` or ES6 classes anymore. The `no-this` rule makes this explicit.
333
334```typescript
335const Message = React.createClass({
336 render: function() {
337 return <div>{this.props.message}</div>; // <- no this allowed
338 }
339});
340```
341
342Instead of creating classes, you should use React 0.14's [Stateless Functional Components](https://medium.com/@joshblack/stateless-components-in-react-0-14-f9798f8b992d#.t5z2fdit6) and save yourself some keystrokes:
343
344```typescript
345const Message = ({ message }) => <div>{message}</div>;
346```
347
348What about lifecycle methods like `shouldComponentUpdate`? We can use the [recompose](https://github.com/acdlite/recompose) library to apply these optimizations to your Stateless Functional Components. The [recompose](https://github.com/acdlite/recompose) library relies on the fact that your Redux state is immutable to efficiently implement shouldComponentUpdate for you.
349
350```typescript
351import { pure, onlyUpdateForKeys } from "recompose";
352
353const Message = ({ message }) => <div>{message}</div>;
354
355// Optimized version of same component, using shallow comparison of props
356// Same effect as React's PureRenderMixin
357const OptimizedMessage = pure(Message);
358
359// Even more optimized: only updates if specific prop keys have changed
360const HyperOptimizedMessage = onlyUpdateForKeys(["message"], Message);
361```
362
363### no-mixed-interface
364
365Mixing functions and data properties in the same interface is a sign of object-orientation style. This rule enforces that an inteface only has one type of members, eg. only data properties or only functions.
366
367### no-expression-statement
368
369When you call a function and don’t use it’s return value, chances are high that it is being called for its side effect. e.g.
370
371```typescript
372array.push(1);
373alert("Hello world!");
374```
375
376This rule checks that the value of an expression is assigned to a variable and thus helps promote side-effect free (pure) functions.
377
378#### Options
379
380* [ignore-prefix](#using-the-ignore-prefix-option-with-no-expression-statement)
381
382#### Example config
383
384```javascript
385"no-expression-statement": true
386```
387
388```javascript
389"no-expression-statement": [true, {"ignore-prefix": "console."}]
390```
391
392```javascript
393"no-expression-statement": [true, {"ignore-prefix": ["console.log", "console.error"]}]
394```
395
396### no-if-statement
397
398If statements is not a good fit for functional style programming as they are not expresssions and do not return a value. This rule disallows if statements.
399
400```typescript
401let x;
402if (i === 1) {
403 x = 2;
404} else {
405 x = 3;
406}
407```
408
409Instead consider using the [tenary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) which is an expression that returns a value:
410
411```typescript
412const x = i === 1 ? 2 : 3;
413```
414
415For more background see this [blog post](https://hackernoon.com/rethinking-javascript-the-if-statement-b158a61cd6cb) and discussion in [#54](https://github.com/jonaskello/tslint-immutable/issues/54).
416
417### no-loop-statement
418
419In functional programming we want everthing to be an expression that returns a value. Loops in typescript are statements so they are not a good fit for a functional programming style. This rule disallows for loop statements, including `for`, `for...of`, `for...in`, `while`, and `do...while`.
420
421```typescript
422const numbers = [1, 2, 3];
423const double = [];
424for (let i = 0; i < numbers.length; i++) {
425 double[i] = numbers[i] * 2;
426}
427```
428
429Instead consider using `map` or `reduce`:
430
431```typescript
432const numbers = [1, 2, 3];
433const double = numbers.map(n => n * 2);
434```
435
436For more background see this [blog post](https://hackernoon.com/rethinking-javascript-death-of-the-for-loop-c431564c84a8) and discussion in [#54](https://github.com/jonaskello/tslint-immutable/issues/54).
437
438### no-throw
439
440Exceptions are not part of functional programming.
441
442```typescript
443throw new Error("Something went wrong."); // Unexpected throw, throwing exceptions is not functional.
444```
445
446As an alternative a function should return an error:
447
448```typescript
449function divide(x: number, y: number): number | Error {
450 return y === 0 ? new Error("Cannot divide by zero.") : x / y;
451}
452```
453
454Or in the case of an async function, a rejected promise should be returned:
455
456```typescript
457async function divide(x: Promise<number>, y: Promise<number>): Promise<number> {
458 const [xv, yv] = await Promise.all([x, y]);
459
460 return yv === 0
461 ? Promise.reject(new Error("Cannot divide by zero."))
462 : xv / yv;
463}
464```
465
466### no-try
467
468Try statements are not part of functional programming. See [no-throw](#no-throw) for more information.
469
470## Options
471
472### Using the `ignore-local` option
473
474> If a tree falls in the woods, does it make a sound?
475> If a pure function mutates some local data in order to produce an immutable return value, is that ok?
476
477The quote above is from the [clojure docs](https://clojure.org/reference/transients). In general, it is more important to enforce immutability for state that is passed in and out of functions than for local state used for internal calculations within a function. For example in Redux, the state going in and out of reducers needs to be immutable while the reducer may be allowed to mutate local state in its calculations in order to achieve higher performance. This is what the `ignore-local` option enables. With this option enabled immutability will be enforced everywhere but in local state. Function parameters and return types are not considered local state so they will still be checked.
478
479Note that using this option can lead to more imperative code in functions so use with care!
480
481### Using the `ignore-class` option
482
483Doesn't check for `readonly` in classes.
484
485### Using the `ignore-interface` option
486
487Doesn't check for `readonly` in interfaces.
488
489### Using the `ignore-rest-parameters` option
490
491Doesn't check for `ReadonlyArray` for function rest parameters.
492
493### Using the `ignore-return-type` option
494
495Doesn't check the return type of functions.
496
497### Using the `ignore-prefix` option
498
499Some languages are immutable by default but allows you to explicitly declare mutable variables. For example in [reason](https://facebook.github.io/reason/) you can declare mutable record fields like this:
500
501```reason
502type person = {
503 name: string,
504 mutable age: int
505};
506```
507
508Typescript is not immutable by default but it can be if you use this package. So in order to create an escape hatch similar to how it is done in reason the `ignore-prefix` option can be used. For example if you configure it to ignore variables with names that has the prefix "mutable" you can emulate the above example in typescript like this:
509
510```typescript
511type person = {
512 readonly name: string;
513 mutableAge: number; // This is OK with ignore-prefix = "mutable"
514};
515```
516
517Yes, variable names like `mutableAge` are ugly, but then again mutation is an ugly business :-).
518
519### Using the `ignore-prefix` option with `no-expression-statement`
520
521Expression statements typically cause side effects, however not all side effects are undesirable. One example of a helpful side effect is logging. To not get warning of every log statement, we can configure the linter to ignore well known expression statement prefixes.
522
523One such prefix could be `console.`, which would cover both these cases:
524
525```typescript
526const doSomething(arg:string) => {
527 if (arg) {
528 console.log("Argument is", arg);
529 } else {
530 console.warn("Argument is empty!");
531 }
532 return `Hello ${arg}`;
533}
534```
535
536### Using the `ignore-new-array` option with `no-array-mutation`
537
538This option allows for the use of array mutator methods to be chained to newly created arrays.
539
540For example, an array can be immutably sorted like so:
541
542```typescript
543const original = ["foo", "bar", "baz"];
544const sorted = original.slice().sort((a, b) => a.localeCompare(b)); // This is OK with ignore-new-array - note the use of the `slice` method which returns a copy of the original array.
545```
546
547## Recommended built-in rules
548
549### [no-var-keyword](https://palantir.github.io/tslint/rules/no-var-keyword/)
550
551Without this rule, it is still possible to create `var` variables that are mutable.
552
553### [no-parameter-reassignment](https://palantir.github.io/tslint/rules/no-parameter-reassignment/)
554
555Without this rule, function parameters are mutable.
556
557### [typedef](https://palantir.github.io/tslint/rules/typedef/) with call-signature option
558
559For performance reasons, tslint-immutable does not check implicit return types. So for example this function will return an mutable array but will not be detected (see [#18](https://github.com/jonaskello/tslint-immutable/issues/18) for more info):
560
561```javascript
562function foo() {
563 return [1, 2, 3];
564}
565```
566
567To avoid this situation you can enable the built in typedef rule like this:
568
569`"typedef": [true, "call-signature"]`
570
571Now the above function is forced to declare the return type becomes this and will be detected.
572
573## Sample Configuration File
574
575Here's a sample TSLint configuration file (tslint.json) that activates all the rules:
576
577```javascript
578{
579 "extends": ["tslint-immutable"],
580 "rules": {
581
582 // Recommended built-in rules
583 "no-var-keyword": true,
584 "no-parameter-reassignment": true,
585 "typedef": [true, "call-signature"],
586
587 // Immutability rules
588 "readonly-keyword": true,
589 "readonly-array": true,
590 "no-let": true,
591 "no-object-mutation": true,
592 "no-delete": true,
593 "no-method-signature": true,
594
595 // Functional style rules
596 "no-this": true,
597 "no-class": true,
598 "no-mixed-interface": true,
599 "no-expression-statement": true,
600 "no-if-statement": true
601
602 }
603}
604```
605
606It is also possible to enable all the rules in tslint-immutable by extending `tslint-immutable/all` like this:
607
608```javascript
609{
610 "extends": ["tslint-immutable/all"]
611}
612```
613
614## How to contribute
615
616For new features file an issue. For bugs, file an issue and optionally file a PR with a failing test. Tests are really easy to do, you just have to edit the `*.ts.lint` files under the test directory. Read more here about [tslint testing](https://palantir.github.io/tslint/develop/testing-rules/).
617
618## How to develop
619
620To execute the tests first run `yarn build` and then run `yarn test`.
621
622While working on the code you can run `yarn test:work`. This script also builds before running the tests. To run a subset of the tests, change the path for `yarn test:work` in `package.json`.
623
624Please review the [tslint performance tips](https://palantir.github.io/tslint/develop/custom-rules/performance-tips.html) in order to write rules that run efficiently at run-time. For example, note that using `SyntaxWalker` or any subclass thereof like `RuleWalker` is inefficient. Note that tslint requires the use of `class` as an entrypoint, but you can make a very small class that inherits from `AbstractRule` which directly calls `this.applyWithFunction` and from there you can switch to using a more functional programming style.
625
626In order to know which AST nodes are created for a snippet of typescript code you can use [ast explorer](https://astexplorer.net/).
627
628To release a new package version run `yarn publish:patch`, `yarn publish:minor`, or `yarn publish:major`.
629
630## Prior work
631
632This work was originally inspired by [eslint-plugin-immutable](https://github.com/jhusain/eslint-plugin-immutable).
633
634[version-image]: https://img.shields.io/npm/v/tslint-immutable.svg?style=flat
635[version-url]: https://www.npmjs.com/package/tslint-immutable
636[travis-image]: https://travis-ci.com/jonaskello/tslint-immutable.svg?branch=master&style=flat
637[travis-url]: https://travis-ci.com/jonaskello/tslint-immutable
638[codecov-image]: https://codecov.io/gh/jonaskello/tslint-immutable/branch/master/graph/badge.svg
639[codecov-url]: https://codecov.io/gh/jonaskello/tslint-immutable
640[license-image]: https://img.shields.io/github/license/jonaskello/tslint-immutable.svg?style=flat
641[license-url]: https://opensource.org/licenses/MIT
642[prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat
643[prettier-url]: https://github.com/prettier/prettier
644[type-info-badge]: https://img.shields.io/badge/type_info-required-d51313.svg?style=flat
645[type-info-url]: https://palantir.github.io/tslint/usage/type-checking