Skip to content
Svelte Helpers
Language:en Author:AtomForge

Runtime helpers

as

as is a type assertion helper for templates and snippets, where TypeScript annotations are awkward. Every form returns the original value unchanged. It does not validate, convert, or make a wrong assertion safe.

Primitive shorthands

{@const on = as.boolean(td[k])}
{@const label = as.string(item.value)}
{@render list(as.array<string>(items))}

Available: as.string, as.number, as.boolean, as.array, as.object, as.function, as.any, as.unknown.

Generic form

const user = as<{ name: string; age: number }>(userData);

Script-side casters

For types you use repeatedly, create a caster once in the script block:

<script lang="ts">
  import { as } from "@atom-forge/svelte-helpers";

  const toTask = as<{ title: string; done: boolean }>;
  const toKey = as<keyof TableData>;
</script>

{@const task = toTask(_task)}
{@const on = as.boolean(td[toKey(k)])}

Typing snippet parameters

Prefer a script-side caster to inline annotations on snippet parameters:

<script lang="ts">
  import { as } from "@atom-forge/svelte-helpers";
  const itemArgType = as<{ title: string }>;
</script>

{#snippet item(_task)}
  {@const task = itemArgType(_task)}
  {task.title}
{/snippet}

debounce and debounceAsync

Both are trailing-edge debouncers: each call resets a timer, and only the latest arguments run once calls stop for the delay. The default delay is 300 ms.

const handleInput = debounce((val) => {
  console.log(val);
}, 300);

const search = debounceAsync(async (query) => {
  return await api.fetch(query);
}, 500);

debounce returns void. debounceAsync returns a promise for the callback result.

RenderSnippet

Some APIs expect a component, but you hold a snippet. RenderSnippet bridges the two. Both props are required: snippet accepts one argument object (Snippet<[Params]>), and args supplies that object.

<RenderSnippet {snippet} args={{ item, index }} />

It simply calls {@render snippet(args)}, with no fallback for a missing snippet.

Prerequisites (1)

  • variant-props

Teaches (1)

  • runtime-helpers