Skip to content

Commit e9afe90

Browse files
committed
fix: don't remove non-null-assertion operator
#2248
1 parent c6a7994 commit e9afe90

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

packages/svelte2tsx/src/utils/htmlxparser.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ const possibleOperatorOrPropertyAccess = new Set([
152152
'-'
153153
]);
154154

155+
const id_char = /[\w$]/;
156+
155157
function blankPossiblyErrorOperatorOrPropertyAccess(htmlx: string) {
156158
let index = htmlx.indexOf('}');
157159
let lastIndex = 0;
@@ -162,6 +164,16 @@ function blankPossiblyErrorOperatorOrPropertyAccess(htmlx: string) {
162164
while (backwardIndex > lastIndex) {
163165
const char = htmlx.charAt(backwardIndex);
164166
if (possibleOperatorOrPropertyAccess.has(char)) {
167+
if (char === '!') {
168+
// remove ! if it's at the beginning but not if it's used as the TS non-null assertion operator
169+
let prev = backwardIndex - 1;
170+
while (prev > lastIndex && htmlx.charAt(prev) === ' ') {
171+
prev--;
172+
}
173+
if (id_char.test(htmlx.charAt(prev))) {
174+
break;
175+
}
176+
}
165177
const isPlusOrMinus = char === '+' || char === '-';
166178
const isIncrementOrDecrement =
167179
isPlusOrMinus && htmlx.charAt(backwardIndex - 1) === char;

packages/svelte2tsx/test/htmlx2jsx/samples/ts-in-template.v5/expected-svelte5.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,5 @@ item as string;
2121
;__sveltets_2_ensureSnippet(foo(bar as string));
2222

2323
{ svelteHTML.createElement("button", { "onclick":(e: Event) => {e as any},}); }
24-
{ const $$_tnenopmoC0C = __sveltets_2_ensureComponent(Component); new $$_tnenopmoC0C({ target: __sveltets_2_any(), props: { "attr":attr as boolean,}});}
24+
{ const $$_tnenopmoC0C = __sveltets_2_ensureComponent(Component); new $$_tnenopmoC0C({ target: __sveltets_2_any(), props: { "attr":attr as boolean,}});}
25+
{ svelteHTML.createElement("label", { "id":ok!,}); }

packages/svelte2tsx/test/htmlx2jsx/samples/ts-in-template.v5/input.svelte

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@
3030

3131
<button onclick={(e: Event) => {e as any}}>click</button>
3232
<Component attr={attr as boolean} />
33+
<label id={ok!}></label>

0 commit comments

Comments
 (0)