Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(eslint-plugin): add prefer-readonly-parameters (#1513)
- Loading branch information
1 parent
b097245
commit 3be9854
Showing
9 changed files
with
952 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
163 changes: 163 additions & 0 deletions
163
packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
# Requires that function parameters are typed as readonly to prevent accidental mutation of inputs (`prefer-readonly-parameter-types`) | ||
|
||
Mutating function arguments can lead to confusing, hard to debug behavior. | ||
Whilst it's easy to implicitly remember to not modify function arguments, explicitly typing arguments as readonly provides clear contract to consumers. | ||
This contract makes it easier for a consumer to reason about if a function has side-effects. | ||
|
||
## Rule Details | ||
|
||
This rule allows you to enforce that function parameters resolve to readonly types. | ||
A type is considered readonly if: | ||
|
||
- it is a primitive type (`string`, `number`, `boolean`, `symbol`, or an enum), | ||
- it is a function signature type, | ||
- it is a readonly array type whose element type is considered readonly. | ||
- it is a readonly tuple type whose elements are all considered readonly. | ||
- it is an object type whose properties are all marked as readonly, and whose values are all considered readonly. | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```ts | ||
function array1(arg: string[]) {} // array is not readonly | ||
function array2(arg: readonly string[][]) {} // array element is not readonly | ||
function array3(arg: [string, number]) {} // tuple is not readonly | ||
function array4(arg: readonly [string[], number]) {} // tuple element is not readonly | ||
// the above examples work the same if you use ReadonlyArray<T> instead | ||
|
||
function object1(arg: { prop: string }) {} // property is not readonly | ||
function object2(arg: { readonly prop: string; prop2: string }) {} // not all properties are readonly | ||
function object3(arg: { readonly prop: { prop2: string } }) {} // nested property is not readonly | ||
// the above examples work the same if you use Readonly<T> instead | ||
|
||
interface CustomArrayType extends ReadonlyArray<string> { | ||
prop: string; // note: this property is mutable | ||
} | ||
function custom1(arg: CustomArrayType) {} | ||
|
||
interface CustomFunction { | ||
(): void; | ||
prop: string; // note: this property is mutable | ||
} | ||
function custom2(arg: CustomFunction) {} | ||
|
||
function union(arg: string[] | ReadonlyArray<number[]>) {} // not all types are readonly | ||
|
||
// rule also checks function types | ||
interface Foo { | ||
(arg: string[]): void; | ||
} | ||
interface Foo { | ||
new (arg: string[]): void; | ||
} | ||
const x = { foo(arg: string[]): void; }; | ||
function foo(arg: string[]); | ||
type Foo = (arg: string[]) => void; | ||
interface Foo { | ||
foo(arg: string[]): void; | ||
} | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```ts | ||
function array1(arg: readonly string[]) {} | ||
function array2(arg: readonly (readonly string[])[]) {} | ||
function array3(arg: readonly [string, number]) {} | ||
function array4(arg: readonly [readonly string[], number]) {} | ||
// the above examples work the same if you use ReadonlyArray<T> instead | ||
|
||
function object1(arg: { readonly prop: string }) {} | ||
function object2(arg: { readonly prop: string; readonly prop2: string }) {} | ||
function object3(arg: { readonly prop: { readonly prop2: string } }) {} | ||
// the above examples work the same if you use Readonly<T> instead | ||
|
||
interface CustomArrayType extends ReadonlyArray<string> { | ||
readonly prop: string; | ||
} | ||
function custom1(arg: CustomArrayType) {} | ||
|
||
interface CustomFunction { | ||
(): void; | ||
readonly prop: string; | ||
} | ||
function custom2(arg: CustomFunction) {} | ||
|
||
function union(arg: readonly string[] | ReadonlyArray<number[]>) {} | ||
|
||
function primitive1(arg: string) {} | ||
function primitive2(arg: number) {} | ||
function primitive3(arg: boolean) {} | ||
function primitive4(arg: unknown) {} | ||
function primitive5(arg: null) {} | ||
function primitive6(arg: undefined) {} | ||
function primitive7(arg: any) {} | ||
function primitive8(arg: never) {} | ||
function primitive9(arg: string | number | undefined) {} | ||
|
||
function fnSig(arg: () => void) {} | ||
|
||
enum Foo { a, b } | ||
function enum(arg: Foo) {} | ||
|
||
function symb1(arg: symbol) {} | ||
const customSymbol = Symbol('a'); | ||
function symb2(arg: typeof customSymbol) {} | ||
|
||
// function types | ||
interface Foo { | ||
(arg: readonly string[]): void; | ||
} | ||
interface Foo { | ||
new (arg: readonly string[]): void; | ||
} | ||
const x = { foo(arg: readonly string[]): void; }; | ||
function foo(arg: readonly string[]); | ||
type Foo = (arg: readonly string[]) => void; | ||
interface Foo { | ||
foo(arg: readonly string[]): void; | ||
} | ||
``` | ||
|
||
## Options | ||
|
||
```ts | ||
interface Options { | ||
checkParameterProperties?: boolean; | ||
} | ||
|
||
const defaultOptions: Options = { | ||
checkParameterProperties: true, | ||
}; | ||
``` | ||
|
||
### `checkParameterProperties` | ||
|
||
This option allows you to enable or disable the checking of parameter properties. | ||
Because parameter properties create properties on the class, it may be undesirable to force them to be readonly. | ||
|
||
Examples of **incorrect** code for this rule with `{checkParameterProperties: true}`: | ||
|
||
```ts | ||
class Foo { | ||
constructor(private paramProp: string[]) {} | ||
} | ||
``` | ||
|
||
Examples of **correct** code for this rule with `{checkParameterProperties: true}`: | ||
|
||
```ts | ||
class Foo { | ||
constructor(private paramProp: readonly string[]) {} | ||
} | ||
``` | ||
|
||
Examples of **correct** code for this rule with `{checkParameterProperties: false}`: | ||
|
||
```ts | ||
class Foo { | ||
constructor( | ||
private paramProp1: string[], | ||
private paramProp2: readonly string[], | ||
) {} | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
packages/eslint-plugin/src/rules/prefer-readonly-parameter-types.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import { | ||
TSESTree, | ||
AST_NODE_TYPES, | ||
} from '@typescript-eslint/experimental-utils'; | ||
import * as util from '../util'; | ||
|
||
type Options = [ | ||
{ | ||
checkParameterProperties?: boolean; | ||
}, | ||
]; | ||
type MessageIds = 'shouldBeReadonly'; | ||
|
||
export default util.createRule<Options, MessageIds>({ | ||
name: 'prefer-readonly-parameter-types', | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: | ||
'Requires that function parameters are typed as readonly to prevent accidental mutation of inputs', | ||
category: 'Possible Errors', | ||
recommended: false, | ||
requiresTypeChecking: true, | ||
}, | ||
schema: [ | ||
{ | ||
type: 'object', | ||
additionalProperties: false, | ||
properties: { | ||
checkParameterProperties: { | ||
type: 'boolean', | ||
}, | ||
}, | ||
}, | ||
], | ||
messages: { | ||
shouldBeReadonly: 'Parameter should be a read only type', | ||
}, | ||
}, | ||
defaultOptions: [ | ||
{ | ||
checkParameterProperties: true, | ||
}, | ||
], | ||
create(context, [{ checkParameterProperties }]) { | ||
const { esTreeNodeToTSNodeMap, program } = util.getParserServices(context); | ||
const checker = program.getTypeChecker(); | ||
|
||
return { | ||
[[ | ||
AST_NODE_TYPES.ArrowFunctionExpression, | ||
AST_NODE_TYPES.FunctionDeclaration, | ||
AST_NODE_TYPES.FunctionExpression, | ||
AST_NODE_TYPES.TSCallSignatureDeclaration, | ||
AST_NODE_TYPES.TSConstructSignatureDeclaration, | ||
AST_NODE_TYPES.TSDeclareFunction, | ||
AST_NODE_TYPES.TSEmptyBodyFunctionExpression, | ||
AST_NODE_TYPES.TSFunctionType, | ||
AST_NODE_TYPES.TSMethodSignature, | ||
].join(', ')]( | ||
node: | ||
| TSESTree.ArrowFunctionExpression | ||
| TSESTree.FunctionDeclaration | ||
| TSESTree.FunctionExpression | ||
| TSESTree.TSCallSignatureDeclaration | ||
| TSESTree.TSConstructSignatureDeclaration | ||
| TSESTree.TSDeclareFunction | ||
| TSESTree.TSEmptyBodyFunctionExpression | ||
| TSESTree.TSFunctionType | ||
| TSESTree.TSMethodSignature, | ||
): void { | ||
for (const param of node.params) { | ||
if ( | ||
!checkParameterProperties && | ||
param.type === AST_NODE_TYPES.TSParameterProperty | ||
) { | ||
continue; | ||
} | ||
|
||
const actualParam = | ||
param.type === AST_NODE_TYPES.TSParameterProperty | ||
? param.parameter | ||
: param; | ||
const tsNode = esTreeNodeToTSNodeMap.get(actualParam); | ||
const type = checker.getTypeAtLocation(tsNode); | ||
const isReadOnly = util.isTypeReadonly(checker, type); | ||
|
||
if (!isReadOnly) { | ||
context.report({ | ||
node: actualParam, | ||
messageId: 'shouldBeReadonly', | ||
}); | ||
} | ||
} | ||
}, | ||
}; | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.