diff --git a/packages/svelte2tsx/src/svelte2tsx/processInstanceScriptContent.ts b/packages/svelte2tsx/src/svelte2tsx/processInstanceScriptContent.ts
index a3eaad0e8..e226c2b1b 100644
--- a/packages/svelte2tsx/src/svelte2tsx/processInstanceScriptContent.ts
+++ b/packages/svelte2tsx/src/svelte2tsx/processInstanceScriptContent.ts
@@ -203,7 +203,10 @@ export function processInstanceScriptContent(
if (ts.isVariableDeclaration(node)) {
events.checkIfIsStringLiteralDeclaration(node);
events.checkIfDeclarationInstantiatedEventDispatcher(node);
- implicitStoreValues.addVariableDeclaration(node);
+ // Only top level declarations can be stores
+ if (node.parent?.parent?.parent === tsAst) {
+ implicitStoreValues.addVariableDeclaration(node);
+ }
}
if (ts.isCallExpression(node)) {
diff --git a/packages/svelte2tsx/test/svelte2tsx/samples/$store-nested-declaration/expectedv2.ts b/packages/svelte2tsx/test/svelte2tsx/samples/$store-nested-declaration/expectedv2.ts
new file mode 100644
index 000000000..25db68b0d
--- /dev/null
+++ b/packages/svelte2tsx/test/svelte2tsx/samples/$store-nested-declaration/expectedv2.ts
@@ -0,0 +1,14 @@
+///
+;function render() {
+
+ function x(tr) {
+ for (let notAStore of tr.effects) {}
+ }
+
+ $notAStore;
+;
+async () => {};
+return { props: /** @type {Record} */ ({}), slots: {}, events: {} }}
+
+export default class Input__SvelteComponent_ extends __sveltets_2_createSvelte2TsxComponent(__sveltets_2_partial(__sveltets_2_with_any_event(render()))) {
+}
\ No newline at end of file
diff --git a/packages/svelte2tsx/test/svelte2tsx/samples/$store-nested-declaration/input.svelte b/packages/svelte2tsx/test/svelte2tsx/samples/$store-nested-declaration/input.svelte
new file mode 100644
index 000000000..4d5f2c0e5
--- /dev/null
+++ b/packages/svelte2tsx/test/svelte2tsx/samples/$store-nested-declaration/input.svelte
@@ -0,0 +1,7 @@
+