language-tools: Typescript control flow inside if/{#if} not working when using $store

When you have a store defined as follows:

import { readable, Readable } from "svelte/store"

const post: Readable<Post|null> = readable(null, /* some code that loads the post asynchronously */)

And then in your template you write:

<h1>{$post.title}</h1>

Then the typescript checker rightly complains Object is possibly 'null'. Then I was hoping that I could make that error disappear by doing this:

{#if $post !== null}
    <h1>{$post.title}</h1>
{/if}

But that has no effect whatsoever. Which kind of makes sense. I understand that typescript may not understand that that is an if-statement.

I can imagine that this would actually not be trivial to implement, but I don’t know, it would be really nice.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 3
  • Comments: 15 (7 by maintainers)

Commits related to this issue

Most upvoted comments

In the meantime, Reassigning to a local variable can be a workaround:

$: storeValue = $store

This should be fixed with VS Code Svelte extension version 104.4.4 and svelte-check version 1.1.36. Note that for svelte-check you also need TypeScript 4.2 or later.

Please let me know if it’s working as expected now. There are still control flow issues unrelated to store usage, these are tracked in #619 .

It’s working for me! I can remove my re-assigment hack. Thanks a lot.

Of course. Just wanted to make sure its not a duplicate before opening it 😃