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

chore: Enable eslint rule no-unnecessary-type-assertion #15260

Merged
merged 5 commits into from Dec 13, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions .eslintrc.cjs
Expand Up @@ -35,6 +35,9 @@ module.exports = {
{
files: ["**/*.ts"],
parser: "@typescript-eslint/parser",
parserOptions: {
project: "./tsconfig.json",
},
plugins: ["@typescript-eslint"],
rules: {
"no-unused-vars": "off",
Expand All @@ -61,6 +64,7 @@ module.exports = {
allowNamedExports: true,
},
],
"@typescript-eslint/no-unnecessary-type-assertion": "error",
},
},
{
Expand Down
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -39,8 +39,8 @@
"@rollup/plugin-node-resolve": "^13.3.0",
"@rollup/plugin-replace": "^4.0.0",
"@types/node": "^18.11.7",
"@typescript-eslint/eslint-plugin": "^5.41.0",
"@typescript-eslint/parser": "^5.41.0",
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"babel-plugin-transform-charcodes": "^0.2.0",
"c8": "^7.12.0",
"chalk": "^5.0.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-cli/src/babel/watcher.ts
Expand Up @@ -123,7 +123,7 @@ export function updateExternalDependencies(
}

function removeFileDependency(filename: string, dep: string) {
const deps = depToFiles.get(dep) as Set<string>;
const deps = depToFiles.get(dep);
deps.delete(filename);

if (deps.size === 0) {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/src/config/files/configuration.ts
Expand Up @@ -226,7 +226,7 @@ export function* findRelativeConfig(
envName,
caller,
packageData.pkg?.dirname === loc
? packageToBabelConfig(packageData.pkg as ConfigFile)
? packageToBabelConfig(packageData.pkg)
: null,
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/src/config/files/module-types.ts
Expand Up @@ -59,7 +59,7 @@ function guessJSModuleType(filename: string): "cjs" | "mjs" | "unknown" {
}

function loadCjsDefault(filepath: string, fallbackToTranspiledModule: boolean) {
const module = endHiddenCallStack(require)(filepath) as any;
const module = endHiddenCallStack(require)(filepath);
return module?.__esModule
? // TODO (Babel 8): Remove "module" and "undefined" fallback
module.default || (fallbackToTranspiledModule ? module : undefined)
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/src/gensync-utils/async.ts
Expand Up @@ -28,7 +28,7 @@ export function maybeAsync<Args extends unknown[], Return>(
): Gensync<Args, Return> {
return gensync({
sync(...args) {
const result = fn.apply(this, args) as Return;
const result = fn.apply(this, args);
if (isThenable(result)) throw new Error(message);
return result;
},
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-core/src/transformation/normalize-file.ts
Expand Up @@ -45,7 +45,7 @@ export default function* normalizeFile(
}

if (options.cloneInputAst) {
ast = cloneDeep(ast) as t.File;
ast = cloneDeep(ast);
}
} else {
// @ts-expect-error todo: use babel-types ast typings in Babel parser
Expand Down
Expand Up @@ -487,6 +487,7 @@ const privateNameHandlerLoose: Handler<PrivateNameState> = {
boundGet(member) {
return t.callExpression(
t.memberExpression(this.get(member), t.identifier("bind")),
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
[t.cloneNode(member.node.object as t.Expression)],
);
},
Expand Down Expand Up @@ -1045,7 +1046,7 @@ export function buildFieldsInitNodes(
// We special-case the single expression case to avoid the iife, since
// it's common.
if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) {
staticNodes.push(blockBody[0] as t.ExpressionStatement);
staticNodes.push(blockBody[0]);
} else {
staticNodes.push(template.statement.ast`(() => { ${blockBody} })()`);
}
Expand Down
14 changes: 7 additions & 7 deletions packages/babel-helper-create-class-features-plugin/src/index.ts
Expand Up @@ -190,7 +190,7 @@ export function createClassFeaturePlugin({
const privateNamesMap = buildPrivateNamesMap(props);
const privateNamesNodes = buildPrivateNamesNodes(
privateNamesMap,
(privateFieldsAsProperties ?? loose) as boolean,
privateFieldsAsProperties ?? loose,
file,
);

Expand Down Expand Up @@ -230,9 +230,9 @@ export function createClassFeaturePlugin({
props,
privateNamesMap,
file,
(setPublicClassFields ?? loose) as boolean,
(privateFieldsAsProperties ?? loose) as boolean,
(constantSuper ?? loose) as boolean,
setPublicClassFields ?? loose,
privateFieldsAsProperties ?? loose,
constantSuper ?? loose,
innerBinding,
));
}
Expand All @@ -245,9 +245,9 @@ export function createClassFeaturePlugin({
props,
privateNamesMap,
file,
(setPublicClassFields ?? loose) as boolean,
(privateFieldsAsProperties ?? loose) as boolean,
(constantSuper ?? loose) as boolean,
setPublicClassFields ?? loose,
privateFieldsAsProperties ?? loose,
constantSuper ?? loose,
innerBinding,
));
}
Expand Down
Expand Up @@ -283,6 +283,7 @@ const handle = {
"=",
context,
// object must not be Super when `context` is an identifier
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
object as t.Expression,
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-node/src/_babel-node.ts
Expand Up @@ -258,7 +258,7 @@ function replStart() {
useGlobal: true,
preview: true,
});
const NODE_REPL_HISTORY = process.env.NODE_REPL_HISTORY as string;
const NODE_REPL_HISTORY = process.env.NODE_REPL_HISTORY;
if (process.env.BABEL_8_BREAKING) {
replServer.setupHistory(NODE_REPL_HISTORY, () => {});
} else {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-node/src/babel-node.ts
Expand Up @@ -54,7 +54,7 @@ getV8Flags(async function (err, v8Flags) {
args.push(flag);
args.push(babelArgs[++i]);
} else if (aliases.has(flag)) {
args.unshift(aliases.get(flag) as string);
args.unshift(aliases.get(flag));
} else if (
flag === "debug" || // node debug foo.js
flag === "inspect" ||
Expand Down
5 changes: 1 addition & 4 deletions packages/babel-parser/src/parser/expression.ts
Expand Up @@ -63,7 +63,6 @@ import {
PARAM_RETURN,
functionFlags,
} from "../util/production-parameter";
import type { ParamKind } from "../util/production-parameter";
import {
newArrowHeadScope,
newAsyncArrowScope,
Expand Down Expand Up @@ -2558,9 +2557,7 @@ export default abstract class ExpressionParser extends LValParser {

// FunctionBody[Yield, Await]:
// StatementList[?Yield, ?Await, +Return] opt
this.prodParam.enter(
(this.prodParam.currentFlags() | PARAM_RETURN) as ParamKind,
);
this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
node.body = this.parseBlock(
true,
false,
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-parser/src/parser/util.ts
Expand Up @@ -175,7 +175,7 @@ export default abstract class UtilParser extends Tokenizer {
this.state.tokensLength = failState.tokensLength;
return {
node,
error: failState.errors[oldState.errors.length] as ParseError<any>,
error: failState.errors[oldState.errors.length],
thrown: false,
aborted: false,
failState,
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-parser/src/plugins/estree.ts
Expand Up @@ -501,7 +501,7 @@ export default (superClass: typeof Parser) =>
break;
}

return node as N.AnyExport;
return node;
}

parseSubscript(
Expand Down
9 changes: 2 additions & 7 deletions packages/babel-parser/src/plugins/jsx/index.ts
Expand Up @@ -480,15 +480,10 @@ export default (superClass: typeof Parser) =>
this.setContext(tc.brace);
this.next();
if (this.match(tt.ellipsis)) {
children.push(
this.jsxParseSpreadChild(node as Undone<N.JSXSpreadChild>),
);
children.push(this.jsxParseSpreadChild(node));
} else {
children.push(
this.jsxParseExpressionContainer(
node as Undone<N.JSXExpressionContainer>,
tc.j_expr,
),
this.jsxParseExpressionContainer(node, tc.j_expr),
Comment on lines -483 to +486
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only here they might not be very good, but just two are fine.

);
}

Expand Down
13 changes: 5 additions & 8 deletions packages/babel-parser/src/plugins/typescript/index.ts
Expand Up @@ -1097,7 +1097,7 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
!type.typeParameters &&
type.typeName.type === "Identifier"
) {
labeledNode.label = type.typeName as N.Identifier;
labeledNode.label = type.typeName;
} else {
this.raise(TSErrors.InvalidTupleMemberLabel, { at: type });
// @ts-expect-error This produces an invalid AST, but at least we don't drop
Expand Down Expand Up @@ -1482,13 +1482,13 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
// if it turns out to be a `TSThisType`, wrap it with `TSTypePredicate`
// : asserts this
if (thisTypePredicate.type === "TSThisType") {
node.parameterName = thisTypePredicate as N.TsThisType;
node.parameterName = thisTypePredicate;
node.asserts = true;
(node as N.TsTypePredicate).typeAnnotation = null;
thisTypePredicate = this.finishNode(node, "TSTypePredicate");
} else {
this.resetStartLocationFromNode(thisTypePredicate, node);
(thisTypePredicate as N.TsTypePredicate).asserts = true;
thisTypePredicate.asserts = true;
}
t.typeAnnotation = thisTypePredicate;
return this.finishNode(t, "TSTypeAnnotation");
Expand Down Expand Up @@ -2094,7 +2094,7 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
if (this.match(tt.braceL)) {
this.scope.enter(SCOPE_TS_MODULE);
this.prodParam.enter(PARAM);
const mod = node as Undone<N.TsModuleDeclaration>;
const mod = node;
mod.global = true;
mod.id = expr;
mod.body = this.tsParseModuleBlock();
Expand Down Expand Up @@ -2880,10 +2880,7 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
at: this.state.curPosition(),
});
}
super.parseClassStaticBlock(
classBody,
member as any as N.StaticBlock,
);
super.parseClassStaticBlock(classBody, member as N.StaticBlock);
} else {
this.parseClassMemberWithIsStatic(
classBody,
Expand Down
3 changes: 1 addition & 2 deletions packages/babel-parser/src/util/production-parameter.ts
Expand Up @@ -75,6 +75,5 @@ export function functionFlags(
isAsync: boolean,
isGenerator: boolean,
): ParamKind {
return ((isAsync ? PARAM_AWAIT : 0) |
(isGenerator ? PARAM_YIELD : 0)) as ParamKind;
return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
}
Expand Up @@ -7,8 +7,8 @@ import type * as t from "@babel/types";
export default declare(api => {
api.assertVersion(7);

const noDocumentAll = (api.assumption("noDocumentAll") ?? false) as boolean;
const pureGetters = (api.assumption("pureGetters") ?? false) as boolean;
const noDocumentAll = api.assumption("noDocumentAll") ?? false;
const pureGetters = api.assumption("pureGetters") ?? false;

return {
name: "bugfix-v8-spread-parameters-in-optional-chaining",
Expand Down
Expand Up @@ -7,7 +7,6 @@ import {
FEATURES,
} from "@babel/helper-create-class-features-plugin";

import type * as t from "@babel/types";
/**
* Generate a uid that is not in `denyList`
*
Expand Down Expand Up @@ -65,7 +64,7 @@ export default declare(({ types: t, template, assertVersion }) => {
// We special-case the single expression case to avoid the iife, since
// it's common.
if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) {
replacement = (blockBody[0] as t.ExpressionStatement).expression;
replacement = blockBody[0].expression;
} else {
replacement = template.expression.ast`(() => { ${blockBody} })()`;
}
Expand Down
Expand Up @@ -610,7 +610,7 @@ function transformClass(
let name = "computedKey";

if (isPrivate) {
name = (key as t.PrivateName).id.name;
name = key.id.name;
} else if (!isComputed && key.type === "Identifier") {
name = key.name;
}
Expand Down Expand Up @@ -653,7 +653,7 @@ function transformClass(
`set_${name}`,
);

addCallAccessorsFor(newPath, key as t.PrivateName, getId, setId);
addCallAccessorsFor(newPath, key, getId, setId);

locals = [newFieldInitId, getId, setId];
} else {
Expand All @@ -678,12 +678,12 @@ function transformClass(
locals = initId;

if (isPrivate) {
privateMethods = extractProxyAccessorsFor(key as t.PrivateName);
privateMethods = extractProxyAccessorsFor(key);
}
} else if (isPrivate) {
locals = element.scope.parent.generateDeclaredUidIdentifier(
`call_${name}`,
) as t.Identifier;
);

const replaceSupers = new ReplaceSupers({
constantSuper,
Expand Down Expand Up @@ -712,7 +712,7 @@ function transformClass(
if (kind === GETTER || kind === SETTER) {
movePrivateAccessor(
element as NodePath<t.ClassPrivateMethod>,
t.cloneNode(key as t.PrivateName),
t.cloneNode(key),
t.cloneNode(locals),
isStatic,
);
Expand All @@ -721,15 +721,10 @@ function transformClass(

// Unshift
path.node.body.body.unshift(
t.classPrivateProperty(
key as t.PrivateName,
t.cloneNode(locals),
[],
node.static,
),
t.classPrivateProperty(key, t.cloneNode(locals), [], node.static),
);

decoratedPrivateMethods.add((key as t.PrivateName).id.name);
decoratedPrivateMethods.add(key.id.name);

element.remove();
}
Expand Down
Expand Up @@ -28,6 +28,7 @@ export default declare(api => {
"=",
t.cloneNode(memo),
// object must not be Super when `memo` is an identifier
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
object as t.Expression,
);
}
Expand Down
Expand Up @@ -412,8 +412,7 @@ export default declare((api, opts: Options) => {
if (path.isObjectProperty()) {
refPropertyPath.unshift(path);
} else if (path.isVariableDeclarator()) {
kind = (path.parentPath as NodePath<t.VariableDeclaration>).node
.kind;
kind = path.parentPath.node.kind;
return true;
}
});
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-plugin-proposal-optional-chaining/src/index.ts
Expand Up @@ -11,8 +11,8 @@ export default declare((api, options: Options) => {
api.assertVersion(7);

const { loose = false } = options;
const noDocumentAll = (api.assumption("noDocumentAll") ?? loose) as boolean;
const pureGetters = (api.assumption("pureGetters") ?? loose) as boolean;
const noDocumentAll = api.assumption("noDocumentAll") ?? loose;
const pureGetters = api.assumption("pureGetters") ?? loose;

return {
name: "proposal-optional-chaining",
Expand Down
Expand Up @@ -141,6 +141,7 @@ export function transform(
// Here `chainWithTypes` MUST NOT be cloned because it could be
// updated when generating the memoised context of a call
// expression. It must be an Expression when `ref` is an identifier
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
chainWithTypes as t.Expression,
);

Expand Down Expand Up @@ -189,7 +190,8 @@ export function transform(
// object must not be Super as super?.foo is invalid
const object = skipTransparentExprWrapperNodes(
replacement.object,
) as t.Expression;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
) as any as t.Expression;
let baseRef;
if (!pureGetters || !isSimpleMemberExpression(object)) {
// memoize the context object when getters are not always pure
Expand Down