TSLint rules to disable mutation in TypeScript.
TSLint rules to disable mutation in TypeScript.
:warning: TSLint will be deprecated some time in 2019. See this issue for more details: Roadmap: TSLint → ESLint.
:rocket: Work has started to port these rules to a new eslint plugin over at the eslint-plugin-functional repo. Please head over there and give it a :star: :-).
In 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.
I originally used immutablejs 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 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).
Then typescript 2.0 came along and introduced readonly 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.
This 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.
npm install tslint-immutable --save-dev
See the example tslint.json file for configuration.
In addition to immutable rules this project also contains a few rules for enforcing a functional style of programming. The following rules are available:
This rule enforces use of the
readonlymodifier. The
readonlymodifier can appear on property signatures in interfaces, property declarations in classes, and index signatures.
Below is some information about the
readonlymodifier and the benefits of using it:
You might think that using
constwould eliminate mutation from your TypeScript code. Wrong. Turns out that there's a pretty big loophole in
const.
interface Point { x: number; y: number; } const point: Point = { x: 23, y: 44 }; point.x = 99; // This is legal
This is why the
readonlymodifier exists. It prevents you from assigning a value to the result of a member expression.
interface Point { readonly x: number; readonly y: number; } const point: Point = { x: 23, y: 44 }; point.x = 99; //This is just as effective as using Object.freeze() to prevent mutations in your Redux reducers. However the
readonlymodifier 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 that was added in typescript 2.1:interface Point { readonly x: number; readonly y: number; } const point: Point = { x: 23, y: 44 }; const transformedPoint = { ...point, x: 99 };Note that you can also use object spread when destructuring to delete keys in an object:
let { [action.id]: deletedItem, ...rest } = state;The
readonlymodifier also works on indexers:const foo: { readonly [key: string]: number } = { a: 1, b: 2 }; foo["a"] = 3; // Error: Index signature only permits readingHas Fixer
Yes
Options
"readonly-keyword": true
"readonly-keyword": [true, "ignore-local"]
"readonly-keyword": [true, "ignore-local", {"ignore-prefix": "mutable"}]
This rule enforces use of
ReadonlyArrayor
readonly T[]instead of
Arrayor
T[].
Below is some information about the
ReadonlyArraytype and the benefits of using it:
Even if an array is declared with
constit is still possible to mutate the contents of the array.
interface Point { readonly x: number; readonly y: number; } const points: Array = [{ x: 23, y: 44 }]; points.push({ x: 1, y: 2 }); // This is legal
Using the
ReadonlyArraytype or
readonly T[]will stop this mutation:
interface Point { readonly x: number; readonly y: number; }const points: ReadonlyArray = [{ x: 23, y: 44 }]; // const points: readonly Point[] = [{ x: 23, y: 44 }]; // This is the alternative syntax for the line above
points.push({ x: 1, y: 2 }); // Unresolved method push()
Yes
"readonly-array": true
"readonly-array": [true, "ignore-local"]
"readonly-array": [true, "ignore-local", {"ignore-prefix": "mutable"}]
This rule should be combined with tslint's built-in
no-var-keywordrule to enforce that all variables are declared as
const.
There's no reason to use
letin a Redux/React application, because all your state is managed by either Redux or React. Use
constinstead, and avoid state bugs altogether.
let x = 5; //What about
forloops? Loops can be replaced with the Array methods likemap,filter, and so on. If you find the built-in JS Array methods lacking, use ramda, or lodash-fp.const SearchResults = ({ results }) => (
Yes
"no-let": true
"no-let": [true, "ignore-local"]
"no-let": [true, "ignore-local", {"ignore-prefix": "mutable"}]
This rule prohibits mutating an array via assignment to or deletion of their elements/properties. This rule enforces array immutability without the use of
ReadonlyArray(as apposed to readonly-array).
const x = [0, 1, 2];x[0] = 4; //
Has Fixer
No
Options
"no-array-mutation": true
"no-array-mutation": [true, {"ignore-prefix": "mutable"}]
"no-array-mutation": [true, "ignore-new-array"]
This rule prohibits syntax that mutates existing objects via assignment to or deletion of their properties. While requiring the
readonlymodifier 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.
const x = { a: 1 };x.foo = "bar"; //
Has Fixer
No
Options
"no-object-mutation": true
"no-object-mutation": [true, {"ignore-prefix": "mutable"}]
There are two ways function members can be declared in an interface or type alias:
interface Zoo { foo(): string; // MethodSignature, cannot have readonly modifier readonly bar: () => string; // PropertySignature }
The
MethodSignatureand the
PropertySignatureforms seem equivalent, but only the
PropertySignatureform can have a
readonlymodifier. Becuase of this any
MethodSignaturewill be mutable. Therefore the
no-method-signaturerule disallows usage of this form and instead proposes to use the
PropertySignaturewhich can have a
readonlymodifier. It should be noted however that the
PropertySignatureform for declaring functions does not support overloading.
The delete operator allows for mutating objects by deleting keys. This rule disallows any delete expressions.
delete object.property; // Unexpected delete, objects should be considered immutable.
As an alternative the spread operator can be used to delete a key in an object (as noted here):
const { [action.id]: deletedItem, ...rest } = state;
Thanks to libraries like recompose and Redux's React Container components, there's not much reason to build Components using
React.createClassor ES6 classes anymore. The
no-thisrule makes this explicit.
const Message = React.createClass({ render: function() { return{this.props.message}; //Instead of creating classes, you should use React 0.14's Stateless Functional Components and save yourself some keystrokes:
const Message = ({ message }) =>{message};What about lifecycle methods like
shouldComponentUpdate? We can use the recompose library to apply these optimizations to your Stateless Functional Components. The recompose library relies on the fact that your Redux state is immutable to efficiently implement shouldComponentUpdate for you.import { pure, onlyUpdateForKeys } from "recompose";const Message = ({ message }) =>
{message};// Optimized version of same component, using shallow comparison of props // Same effect as React's PureRenderMixin const OptimizedMessage = pure(Message);
// Even more optimized: only updates if specific prop keys have changed const HyperOptimizedMessage = onlyUpdateForKeys(["message"], Message);
no-mixed-interface
Mixing 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.
no-expression-statement
When 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.
array.push(1); alert("Hello world!");This rule checks that the value of an expression is assigned to a variable and thus helps promote side-effect free (pure) functions.
Options
"no-expression-statement": true
"no-expression-statement": [true, {"ignore-prefix": "console."}]
"no-expression-statement": [true, {"ignore-prefix": ["console.log", "console.error"]}]
If 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.
let x; if (i === 1) { x = 2; } else { x = 3; }
Instead consider using the tenary operator which is an expression that returns a value:
const x = i === 1 ? 2 : 3;
For more background see this blog post and discussion in #54.
In 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.
const numbers = [1, 2, 3]; const double = []; for (let i = 0; i < numbers.length; i++) { double[i] = numbers[i] * 2; }
Instead consider using
mapor
reduce:
const numbers = [1, 2, 3]; const double = numbers.map(n => n * 2);
For more background see this blog post and discussion in #54.
Exceptions are not part of functional programming.
throw new Error("Something went wrong."); // Unexpected throw, throwing exceptions is not functional.
As an alternative a function should return an error:
function divide(x: number, y: number): number | Error { return y === 0 ? new Error("Cannot divide by zero.") : x / y; }
Or in the case of an async function, a rejected promise should be returned.
async function divide(x: Promise, y: Promise): Promise { const [xv, yv] = await Promise.all([x, y]);return yv === 0 ? Promise.reject(new Error("Cannot divide by zero.")) : xv / yv; }
Try statements are not part of functional programming. See no-throw for more information.
You can view a
Promiseas a result object with built-in error (something like
{ value: number } | { error: Error }) in which case a rejected
Promisecan be viewed as a returned result and thus fits with functional programming. You can also view a rejected promise as something similar to an exception and as such something that does not fit with functional programming. If your view is the latter you can use the
no-rejectrule to disallow rejected promises.
async function divide( x: Promise, y: Promise ): Promise { const [xv, yv] = await Promise.all([x, y]);// Rejecting the promise is not allowed so resolve to an Error instead
// return yv === 0 // ? Promise.reject(new Error("Cannot divide by zero.")) // : xv / yv;
return yv === 0 ? new Error("Cannot divide by zero.") : xv / yv; }
ignore-localoption
If a tree falls in the woods, does it make a sound? If a pure function mutates some local data in order to produce an immutable return value, is that ok?
The quote above is from the clojure docs. 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-localoption 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.
Note that using this option can lead to more imperative code in functions so use with care!
ignore-classoption
Doesn't check for
readonlyin classes.
ignore-interfaceoption
Doesn't check for
readonlyin interfaces.
ignore-rest-parametersoption
Doesn't check for
ReadonlyArrayfor function rest parameters.
ignore-return-typeoption
Doesn't check the return type of functions.
ignore-prefixoption
Some languages are immutable by default but allows you to explicitly declare mutable variables. For example in reason you can declare mutable record fields like this:
type person = { name: string, mutable age: int };
Typescript 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-prefixoption 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:
type person = { readonly name: string; mutableAge: number; // This is OK with ignore-prefix = "mutable" };
Yes, variable names like
mutableAgeare ugly, but then again mutation is an ugly business :-).
ignore-suffixoption
Like ignore-prefix but with suffix matching instead of prefix matching.
ignore-patternoption
Like ignore-prefix and ignore-suffix but with more control.
This option allows you to specify dot seperated paths what should be ignored.
For example, the following config would ignore all object mutations for all properties that start with "mutable".
{ "no-object-mutation": [true, { "ignore-pattern": "**.mutable*" }] }
The following wildcards can be used when specifing a pattern:
**- Match any depth (including zero). Can only be used as a full accessor.
*- When used as a full accessor, match the next accessor. When used as part of an accessor, match any characters.
ignore-prefixoption with
no-expression-statement
Expression 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.
One such prefix could be
console., which would cover both these cases:
const doSomething(arg:string) => { if (arg) { console.log("Argument is", arg); } else { console.warn("Argument is empty!"); } return `Hello ${arg}`; }
ignore-new-arrayoption with
no-array-mutation
This option allows for the use of array mutator methods to be chained to newly created arrays.
For example, an array can be immutably sorted like so:
const original = ["foo", "bar", "baz"]; const 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.
Without this rule, it is still possible to create
varvariables that are mutable.
Without this rule, function parameters are mutable.
For 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 for more info):
function foo() { return [1, 2, 3]; }
To avoid this situation you can enable the built in typedef rule like this:
"typedef": [true, "call-signature"]
Now the above function is forced to declare the return type becomes this and will be detected.
Here's a sample TSLint configuration file (tslint.json) that activates all the rules:
{ "extends": ["tslint-immutable"], "rules": {// Recommended built-in rules "no-var-keyword": true, "no-parameter-reassignment": true, "typedef": [true, "call-signature"], // Immutability rules "readonly-keyword": true, "readonly-array": true, "no-let": true, "no-object-mutation": true, "no-delete": true, "no-method-signature": true, // Functional style rules "no-this": true, "no-class": true, "no-mixed-interface": true, "no-expression-statement": true, "no-if-statement": true
} }
It is also possible to enable all the rules in tslint-immutable by extending
tslint-immutable/alllike this:
{ "extends": ["tslint-immutable/all"] }
For 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.lintfiles under the test directory. Read more here about tslint testing.
To execute the tests first run
yarn buildand then run
yarn test.
While 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:workin
package.json.
Please review the tslint performance tips in order to write rules that run efficiently at run-time. For example, note that using
SyntaxWalkeror any subclass thereof like
RuleWalkeris inefficient. Note that tslint requires the use of
classas an entrypoint, but you can make a very small class that inherits from
AbstractRulewhich directly calls
this.applyWithFunctionand from there you can switch to using a more functional programming style.
In order to know which AST nodes are created for a snippet of typescript code you can use ast explorer.
yarn version --patch yarn version --minor yarn version --major
This work was originally inspired by eslint-plugin-immutable.