Skip to content

fix(eslint-plugin): [no-unnecessary-type-parameters] descend into all parts of mapped types in no-unnecessary-type-parameters #9530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,16 @@ function collectTypeParameterUsageCounts(
// `isTypeReference` to avoid descending into all the properties of a
// generic interface/class, e.g. `Map<K, V>`.
else if (tsutils.isObjectType(type)) {
visitSymbolsListOnce(type.getProperties(), false);
const properties = type.getProperties();
visitSymbolsListOnce(properties, false);

if (isMappedType(type)) {
visitType(type.typeParameter, false);
if (properties.length === 0) {
// TS treats mapped types like `{[k in "a"]: T}` like `{a: T}`.
// They have properties, so we need to avoid double-counting.
visitType(type.templateType, false);
}
}

for (const typeArgument of type.aliasTypeArguments ?? []) {
Expand Down Expand Up @@ -372,6 +378,8 @@ function collectTypeParameterUsageCounts(

interface MappedType extends ts.ObjectType {
typeParameter?: ts.Type;
constraintType?: ts.Type;
templateType?: ts.Type;
}

function isMappedType(type: ts.Type): type is MappedType {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,12 @@ ruleTester.run('no-unnecessary-type-parameters', rule, {
(token): token is Exclude<TSESTree.Token, Conditions & ExtractedToken> =>
tokenType in conditions;
`,
`
declare function mapObj<K extends string, V>(
obj: { [key in K]?: V },
fn: (key: K, val: V) => number,
): number[];
`,
],

invalid: [
Expand Down Expand Up @@ -608,5 +614,14 @@ ruleTester.run('no-unnecessary-type-parameters', rule, {
code: 'type Fn = <T extends string>() => `a${T}b`;',
errors: [{ messageId: 'sole', data: { name: 'T' } }],
},
{
code: `
declare function mapObj<K extends string, V>(
obj: { [key in K]?: V },
fn: (key: K) => number,
): number[];
`,
errors: [{ messageId: 'sole', data: { name: 'V' } }],
},
],
});
Loading