In Svelte 5 I need to do:
let { foo = 42, bar = 58 } = $props();
to extract the values sent by props with default values. How can I do the same when bar
depends on the value of foo
, like:
// does not work:
let { foo = 42, bar = foo + 1 } = $props();
You will probably need multiple steps and $derived
, e.g.
const props = $props();
const { foo = 42, bar = props.foo + 1 } = $derived(props);
This will not take any default for foo
into account when setting bar
, for that you need to split it further, e.g.
const props = $props();
const { foo, bar } = $derived.by(() => {
const foo = props.foo ?? 42;
const bar = props.bar ?? (foo + 1);
return { foo, bar };
});