-
-
Notifications
You must be signed in to change notification settings - Fork 206
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
TypeScript incorrectly considers variable as possibly null inside condition with array index access #1541
Comments
This is a TypeScript limitation due to the array index access, so there's nothing we can do about it. You get the same error in a regular TS file: let content: {
list: {
image?: {
src: string;
alt: string;
};
}[];
} = null as any;
let item = 0;
if (content.list[item]?.image) {
content.list[item].image.src; // <- error
} |
Hi @dummdidumm, thanks for your answer The difference is that in TypeScript I can mark them as defined ;) if (content.list[item]?.image) {
content.list[item]!.image!.src; // <- no error
} But this is not possible in the markup. |
Having a similar problem: <script lang="ts">
import List from '$components/forms/List.svelte'
type Item = { key: string; value: string }
export let items: Item[]
</script>
<List bind:items let:index>
{#if items[index]} <!-- this check has no effect on the type -->
<!-- Error: Object is possibly 'undefined'. -->
<input bind:value={items[index].key} />
{/if}
</List> I would expect that:
Becasue of the two-way-binding in a loop I can't really store the value in a variable and mark it as defined inside the script tag. Current workaround: <script lang="ts">
import List from '$components/forms/List.svelte'
type Item = { key: string; value: string }
export let items: [Item, ...Item[]] // `tuple` instead of `array`
const typedAs0 = (value: number) => value as 0 // cast to fixed value `0`
</script>
<List bind:items let:index>
{#if items[index]}
<input bind:value={items[typedAs0(index)].key} />
{/if}
</List> |
Describe the bug
TypeScript error "Object is possibly 'undefined' ts(2532)" is shown for nested conditional checks.
This is a special case of fixed #619
Reproduction
Expected behaviour
No error should be thrown
System Info
Dependencies versions:
"svelte": "^3.48.0",
"svelte-check": "^2.7.2",
"svelte-preprocess": "^4.10.7",
"tslib": "^2.4.0",
"typescript": "^4.7.4"
and
Svelte for VS Code v105.18.1
Which package is the issue about?
svelte-check
Additional Information, eg. Screenshots
No response
The text was updated successfully, but these errors were encountered: