Skip to content

Commit

Permalink
feat(eslint-plugin): [no-unnec-type-assertion] allow const assertions (
Browse files Browse the repository at this point in the history
  • Loading branch information
a-tarasyuk committed Mar 18, 2020
1 parent 09d8afc commit f76a1b3
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
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

0 comments on commit f76a1b3

Please sign in to comment.