Open
Description
Describe the problem
Currently, the only documented way to create default props is by destructuring them. While this is fine for small components, larger components benefit from using the props.
prefix.
<script lang="ts">
const props: {
name: string;
age?: number; // how to give age a default value?
} = $props();
</script>
<div>{props.name}</div>
<div>{props.age}</div>
I mean, I can do this:
<script lang="ts">
interface Props {
name: string;
age?: number;
}
const defaultProps = {
age: 40,
};
const props: Props = $props();
const props2 = {...defaultProps, ...props};
</script>
<div>{props2.name}</div>
<div>{props2.age}</div>
...which gives me the correct assignment and proper typing, but it's just an ugly React hack.
Describe the proposed solution
Vue 3 provides the withDefaults
API, which is a rather elegant solution to the problem:
const props = withDefaults(defineProps<{
name: string;
age?: number;
}>(), {
age: 40,
});
Something similar could be added to the Svelte runes API.
Importance
i cannot use svelte without it