Skip to content

Instantly share code, notes, and snippets.

@eps1lon
Created April 13, 2021 08:56
Show Gist options
  • Save eps1lon/9a40a00438fbe6422cdb1edbfd145e32 to your computer and use it in GitHub Desktop.
Save eps1lon/9a40a00438fbe6422cdb1edbfd145e32 to your computer and use it in GitHub Desktop.
catch implicit mutable arrays

no-mutable-arrays

Prevent usage of implicit mutable arrays. As input parameters we almost always want readonly arrays.

This has a probably too many false positives in implementation code.

module.exports = {
meta: {
messages: {
implicitMutable:
"Don't use implicit mutable arrays. Either use readonly arrays with `{{suggestion}}` or make the mutability explicit with `MutableArray<T>`.",
},
},
create(context) {
return {
TSTypeReference(node) {
if (node.typeName.name === 'Array') {
context.report({
node,
messageId: 'implicitMutable',
data: { suggestion: 'ReadonlyArray<T>' },
});
}
},
TSArrayType(node) {
const isReadonly =
node.parent.type === 'TSTypeOperator' && node.parent.operator === 'readonly';
if (!isReadonly) {
context.report({
node,
messageId: 'implicitMutable',
data: { suggestion: 'readonly T[]' },
});
}
},
};
},
};
const eslint = require('eslint');
const rule = require('./no-mutable-arrays');
const ruleTester = new eslint.RuleTester({
parser: require.resolve('@typescript-eslint/parser'),
parserOptions: {
ecmaFeatures: { jsx: true },
},
});
ruleTester.run('no-mutable-arrays', rule, {
valid: [
'type Pass = readonly T[];',
'type Pass = MutableArray<T>;',
'type Pass = ReadonlyArray<T>;',
],
invalid: [
{
code: 'type Fail = T[];',
errors: [
{
message:
"Don't use implicit mutable arrays. Either use readonly arrays with `readonly T[]` or make the mutability explicit with `MutableArray<T>`.",
},
],
},
{
code: 'type Fail = Array<T>;',
errors: [
{
message:
"Don't use implicit mutable arrays. Either use readonly arrays with `ReadonlyArray<T>` or make the mutability explicit with `MutableArray<T>`.",
},
],
},
],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment