mediamonks / frontend-coding-standards

Media.Monks - Frontend Coding Standards
60 stars 23 forks source link

Consider using prefer-readonly-parameter-types eslint rule #77

Open mmnathan opened 3 years ago

mmnathan commented 3 years ago

See: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md

When you pass a value to a function it is not immediately clear whether this function will modify the value itself, see for example Array#sort, or the differences between Array#slice and #splice.

From the perspective of writing a function this means you may unintentionally mutate a value inside a function body, which may lead to subtle bugs later on. From the perspective of the function consumer it is nice to know beforehand whether you can expect a function to modify your data.

Using the prefer-readonly-parameter-types rule you can see from a function signature if it will* mutate your data, and from the inside of the function body you'll get a typescript error when you try to mutate an 'immutable' value.

You can still pass mutable values to params that are typed as readonly (but not the other way around**) due the structural nature of TypeScript, so there's no need to type everything as 'immutable'.

* When it's globally accepted that a param is readonly by default, it becomes only natural that the remaining functions will in fact mutate your data. ** React.Children for example will accept a value typed as Array<ReactElement> but it won’t accept ReadonlyArray<ReactElement>, which is a bit awkward.