fix(es/transforms/typescript): Allow (foo as any) = bar (#2631)

swc_ecma_transforms_typescript:
 - `strip`: Handle paren in the LHS of assignment expressions properly. (Closes https://github.com/swc-project/swc/issues/2606)
This commit is contained in:
OJ Kwon 2021-11-02 19:25:18 -07:00 committed by GitHub
parent 04238d0b93
commit 12be4b1799
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 85 additions and 0 deletions

View File

@ -2217,6 +2217,34 @@ where
d.visit_mut_children_with(self);
d.definite = false;
}
fn visit_mut_pat_or_expr(&mut self, node: &mut PatOrExpr) {
// Coerce bindingident to assign expr where parenthesis exists due to TsAsExpr
// like (warn as any) = v;
// We want to do this _before_ visiting children, otherwise handle_expr
// wipes out TsAsExpr and there's no way to distinguish between
// plain (x) = y vs. (x as any) = y;
match node {
PatOrExpr::Pat(pat) => match &**pat {
Pat::Expr(expr) => match &**expr {
Expr::Paren(ParenExpr { expr, .. }) => match &**expr {
Expr::TsAs(TsAsExpr { expr, .. }) => match &**expr {
Expr::Ident(ident) => {
*node = PatOrExpr::Pat(Box::new(Pat::Ident(ident.clone().into())));
}
_ => (),
},
_ => (),
},
_ => (),
},
_ => (),
},
_ => (),
}
node.visit_mut_children_with(self);
}
}
fn module_ref_to_expr(r: TsModuleRef) -> Expr {

View File

@ -0,0 +1,11 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "es2015"
},
"module": {
"type": "commonjs"
}
}

View File

@ -0,0 +1,17 @@
export function warn() {
throw new Error("this should not be called");
}
export const test = {};
export const test2 = {};
Object.defineProperty(test, "warn", {
get: () => warn,
set: (v) => {
(warn as any) = v;
},
});
Object.defineProperty(test2, "work", {
get: () => warn,
set: (v) => {
warn = v;
},
});

View File

@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.warn = warn;
exports.test2 = exports.test = void 0;
function warn() {
throw new Error("this should not be called");
}
const test = {
};
exports.test = test;
const test2 = {
};
exports.test2 = test2;
Object.defineProperty(test, "warn", {
get: ()=>warn
,
set: (v)=>{
exports.warn = warn = v;
}
});
Object.defineProperty(test2, "work", {
get: ()=>warn
,
set: (v)=>{
exports.warn = warn = v;
}
});