Skip to content

Instantly share code, notes, and snippets.

@peterszerzo
Last active October 23, 2020 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterszerzo/798dac6a828785b299c86e7849a73649 to your computer and use it in GitHub Desktop.
Save peterszerzo/798dac6a828785b299c86e7849a73649 to your computer and use it in GitHub Desktop.
Type guards working like a charm inside Svelte templates
<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