Bug: [no-unnecessary-type-parameters] uses in a mapped type's constraint are missed once TypeScript has cached its template
Before You File a Bug Report Please Confirm You Have Done The Following...
- I have tried restarting my IDE and the issue persists.
- I have updated to the latest version of the packages.
- I have searched for related issues and found none that matched my issue.
- I have read the FAQ and my problem is not listed.
- If I used AI assistance to prepare this issue, I have reviewed and followed the AI Contribution Policy.
Playground Link
Not applicable: the report depends on TypeScript checker state, so the repro below is the minimal deterministic form.
Repro Code
declare function fill<T, Value>(shape: T, value: Value): { [K in keyof T]: Value };
declare function unfill<U>(mapped: { [K in keyof U]: number }): U;
function cold<T>(shape: T, warmed = false) {
return fill(shape, 1);
}
function warm<T>(shape: T, warmed = !unfill(fill(shape, 1))) {
return fill(shape, 1);
}ESLint Config
export default tseslint.config({
languageOptions: { parserOptions: { projectService: true } },
rules: { '@typescript-eslint/no-unnecessary-type-parameters': 'error' },
});tsconfig
{ "compilerOptions": { "strict": true } }Expected Result
Neither function is reported. In both, T is used by shape and by the returned { [K in keyof T]: number }.
Actual Result
warm reports Type parameter T is used only once in the function signature. cold does not.
Additional Info
The rule reads MappedType.templateType, a checker cache that TypeScript populates lazily. For an instantiated mapped type it stays empty until something relates the type to another generic mapped type; here, checking the unfill call does that before the rule visits the return type.
When the cache is populated the rule visits the template instead of the constraint, so uses of a type parameter that appear only in the constraint (keyof T) are missed. Whether it is populated depends on what the checker happened to evaluate first, including other rules' queries, so the same signature can be reported or not depending on surrounding code.
Found while working on #12803.
Source: typescript-eslint/typescript-eslint