Skip to content
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 @@ -2,11 +2,28 @@ import type { TSESTree } from '@typescript-eslint/utils';

import { AST_NODE_TYPES } from '@typescript-eslint/utils';

import { createRule, nullThrows, NullThrowsReasons } from '../util';
import {
createRule,
isReferenceToGlobalFunction,
nullThrows,
NullThrowsReasons,
} from '../util';

export type MessageIds = 'preferConstructor' | 'preferTypeAnnotation';
export type Options = ['constructor' | 'type-annotation'];

const builtInArrays = new Set([
'Float32Array',
'Float64Array',
'Int16Array',
'Int32Array',
'Int8Array',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray',
]);

export default createRule<Options, MessageIds>({
name: 'consistent-generic-constructors',
meta: {
Expand Down Expand Up @@ -63,6 +80,18 @@ export default createRule<Options, MessageIds>({
);
}
}

function isBuiltInArray(typeName: TSESTree.Identifier) {
return (
builtInArrays.has(typeName.name) &&
isReferenceToGlobalFunction(
typeName.name,
typeName,
context.sourceCode,
)
);
}

const [lhsName, rhs] = getLHSRHS();
const lhs = lhsName.typeAnnotation?.typeAnnotation;

Expand All @@ -77,7 +106,8 @@ export default createRule<Options, MessageIds>({
lhs &&
(lhs.type !== AST_NODE_TYPES.TSTypeReference ||
lhs.typeName.type !== AST_NODE_TYPES.Identifier ||
lhs.typeName.name !== rhs.callee.name)
lhs.typeName.name !== rhs.callee.name ||
isBuiltInArray(lhs.typeName))
) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,38 @@ class A {
`,
`
const a = function (a: Foo = new Foo<string>()) {};
`,
`
const a: Float32Array<ArrayBufferLike> = new Float32Array();
export {};
`,
`
const a: Float64Array<ArrayBufferLike> = new Float64Array();
export {};
`,
`
const a: Int16Array<ArrayBufferLike> = new Int16Array();
export {};
`,
`
const a: Int8Array<ArrayBufferLike> = new Int8Array();
export {};
`,
`
const a: Uint16Array<ArrayBufferLike> = new Uint16Array();
export {};
`,
`
const a: Uint32Array<ArrayBufferLike> = new Uint32Array();
export {};
`,
`
const a: Uint8Array<ArrayBufferLike> = new Uint8Array();
export {};
`,
`
const a: Uint8ClampedArray<ArrayBufferLike> = new Uint8ClampedArray();
export {};
`,
{
code: `
Expand Down Expand Up @@ -592,5 +624,22 @@ const a = function (a = new Foo<string>()) {};
const a = function (a: Foo<string> = new Foo()) {};
`,
},
{
code: `
class Float32Array<T> {}
const a: Float32Array<ArrayBufferLike> = new Float32Array();
export {};
`,
errors: [
{
messageId: 'preferConstructor',
},
],
output: `
class Float32Array<T> {}
const a = new Float32Array<ArrayBufferLike>();
export {};
`,
},
],
});
Loading