I’m adding eslint v9 to my TypeScript project, starting with the standard rule set:
eslint.configs.recommended,
...tseslint.configs.strict,
I’d like to keep the rules quite strict, but I’m getting issues with the many prototype (extension) functions I have written. As an example, see this code:
interface MyObject {
name: string
}
declare global {
interface Array<T> { // Error 1: 'T' is defined but never used.
add(this: Array<MyObject>): void
add(this: Array<MyObject>, withName: string | null): void // Error 2: These overloads can be combined into one signature with an optional parameter.
}
}
Array.prototype.add = function(withName: string | null = null) {
let obj = this; // Error 3: Unexpected aliasing of 'this' to local variable.
if (obj.length > 100) { obj = []; }
obj.push({ name: withName ?? 'default name' })
}
This is implementing an add
function that can be used on an array of MyObject
. You can optionally supply a name and if the array gets too big it will reset. A slightly contrived method, but all genuine issues I’m seeing on different prototype functions.
There are three separate issues, but all with the same code – so I’m asking in one go!
Error 1 – @typescript-eslint/no-unused-vars
Array
needs to define a type (T
), but as the functions should only actually accept MyObject
, T
is never used.
Error 2 – @typescript-eslint/unified-signatures
Functions definitions in the interface cannot have default values, and if I remove the first definition, I can no longer call the function with a parameter.
Error 3 – @typescript-eslint/no-this-alias
this = []
causes the error The left-hand side...must be a variable
, so aliasing is required.
Maybe there is a better way to right my code; which I’d love to do if that is the case. Or I could disable the rules; but if the code is correct, surly eslint should not raise an error.
Is it me or eslint? If it’s not me I’ll raise an issue, but wanted to ask about my code first!