linter: typescript: prefer-immutable-constants
So quite frequently I see code such as:
const fooArr = [ 'bar' ];or
const fooObj = { bar: 1 };With the clear intention that fooArr and fooObj should be treated as immutable, such as if they are being used to represent constant values in the program. But TS makes no such guarantees. In this scenario, any code that has these values in scope could mutate these objects and change their contents, changing program behavior at runtime.
The objective of this proposed rule would be to scan for any references to these objects and see if any code tries to mutate them. If so, it would assume it's intentional. Otherwise, it would assume they should be immutable and require them to be annotated with as const so the compiler can enforce this. I think it would also pair nicely with typescript/prefer-readonly-parameter-types.
Examples of incorrect code for this rule:
const fooArr = [ 'bar' ];
const fooObj = { bar: 1 };Examples of correct code for this rule:
const fooArr1 = [ 'bar' ];
fooArr1.push('baz');
const fooObj1 = { bar: 1 };
fooObj1['baz'] = 2;
const fooArr2 = [ 'bar' ] as const;
const fooObj2 = { bar: 1 } as const;Thoughts?
Source: oxc-project/oxc