'Svelte template - Typescript discriminated union - Error 2322
I have a Svelte template which has conditional output of subcomponent based on a object property. Even though the object property is uniquely identifying the type of object, the compiler complains with ts 2322.
//App.ts
<script lang="ts">
import type {CheckboxData, LabelData} from 'Types.js';
import Checkbox from 'Checkbox.svelte';
import Label from 'Label.svelte';
const tags = (CheckboxData | LabelData)[
new CheckboxData(), new LabelData()
]
</script>
{#each tags as tag}
{#if tag.type === "CHECKBOX"}
<Checbkox data={tag}/> // ts 2322 LabelData is not assignable to CheckboxData
{:else if tag.type === "LABEL"}
<Label data={tag}/>
{/if}
{/each}
//end App.ts
// Types.ts
export class CheckboxData {
type: "CHECKBOX";
checked:boolean;
name:string;
}
export class LabelData {
type: "LABEL";
text:string;
for:string;
}
// end Types.ts
// Checbkox.svelte
<script lang="ts">
import type {CheckboxData} from 'Types.js';
export let data:CheckboxData;
</script>
<checkbox checked={data.checked} name={data.name}></checkbox>
// end Checkbox.svelte
// Label.svelte
<script lang="ts">
import type {LabelData} from 'Types.js';
export let data:Label;
</script>
<label for={data.for}>{data.text}</label>
// end Label.svelte
Solution 1:[1]
I missed the literal part of the "equation", discrimination works if the property is defined like this:
type: "CHECKBOX"
not
type:string = "CHECKBOX"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | steakoverflow |
