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.
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 asArray<ReactElement>
but it won’t acceptReadonlyArray<ReactElement>
, which is a bit awkward.