Skip to content
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

fix(eslint-plugin): [no-unnec-type-assertion] allow const assertions #1741

Merged
merged 3 commits into from Mar 18, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -43,6 +43,10 @@ const foo = <number>3;
const foo = 3 as number;
```

```ts
const foo = 'foo' as const;
```

```ts
function foo(x: number | undefined): number {
return x!;
Expand Down
16 changes: 14 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts
@@ -1,4 +1,7 @@
import { TSESTree } from '@typescript-eslint/experimental-utils';
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
import {
isObjectType,
isObjectFlagSet,
Expand Down Expand Up @@ -122,6 +125,14 @@ export default util.createRule<Options, MessageIds>({
return false;
}

function isConstAssertion(node: TSESTree.TypeNode): boolean {
return (
node.type === AST_NODE_TYPES.TSTypeReference &&
node.typeName.type === AST_NODE_TYPES.Identifier &&
node.typeName.name === 'const'
);
}

return {
TSNonNullExpression(node): void {
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
Expand Down Expand Up @@ -201,7 +212,8 @@ export default util.createRule<Options, MessageIds>({
if (
options.typesToIgnore?.includes(
sourceCode.getText(node.typeAnnotation),
)
) ||
isConstAssertion(node.typeAnnotation)
) {
return;
}
Expand Down
Expand Up @@ -130,6 +130,38 @@ function Test(props: {
`,
filename: 'react.tsx',
},
{
code: `
const a = [1, 2];
const b = [3, 4];
const c = [...a, ...b] as const;
`,
},
{
code: `const a = [1, 2] as const;`,
},
{
code: `const a = 'a' as const;`,
},
{
code: `const a = { foo: 'foo' } as const`,
},
{
code: `
const a = [1, 2];
const b = [3, 4];
const c = <const>[...a, ...b];
`,
},
{
code: `const a = <const>[1, 2];`,
},
{
code: `const a = <const>'a';`,
},
{
code: `const a = <const>{ foo: 'foo' };`,
},
],

invalid: [
Expand Down