Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: standard way to provide default prop values with TypeScript #14838

Open
rodrigocfd opened this issue Dec 26, 2024 · 2 comments

Comments

@rodrigocfd
Copy link

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

@rodrigocfd rodrigocfd changed the title Standard way to provide default prop values with TypeScript Feature request: standard way to provide default prop values with TypeScript Dec 26, 2024
@jjones315
Copy link

its suggested to destructure your props, if you do that using defaults is easy.

<script lang="ts">
    interface Props {
        name: string;
        age?: number;
    }

    const { age = 40, name }: Props = $props();
</script>

<div>{name}</div>
<div>{age}</div>

@webJose
Copy link
Contributor

webJose commented Dec 26, 2024

The proposal I would see feasible would be:

<script lang="ts">
interface Props {
  name: string;
  age?: number;
}

const defaultProps = {
  age: 40,
};

const props: Props = $props(defaultProps);
</script>

<div>{props.name}</div>
<div>{props.age}</div>

The left-hand side should still be destructured if $bindable is required on any of the props.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants