Last active
October 23, 2020 15:52
-
-
Save peterszerzo/798dac6a828785b299c86e7849a73649 to your computer and use it in GitHub Desktop.
Type guards working like a charm inside Svelte templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
type Pet = Fish | Bird; | |
interface Fish { | |
type: "fish"; | |
isLarge: boolean; | |
} | |
interface Bird { | |
type: "bird"; | |
isFast: boolean; | |
} | |
// If type guard is removed (`is ...`), the template below doesn't pass `svelte-check` | |
function isFish(pet: Pet): pet is Fish { | |
return pet.type === "fish"; | |
} | |
function isBird(pet: Pet): pet is Bird { | |
return pet.type === "bird"; | |
} | |
let pet: Pet = { | |
type: "fish", | |
isLarge: true, | |
}; | |
</script> | |
{#if isFish(pet)} | |
<p>a {pet.isLarge ? 'large' : 'small'} fish</p> | |
{/if} | |
{#if isBird(pet)} | |
<p>a {pet.isFast ? 'fast' : 'slot'} bird</p> | |
{/if} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment