Skip to content

Feature: Ability to restrict types accepted by component props #14580

@Ocean-OS

Description

@Ocean-OS

Describe the problem

Sometimes when making components, you want to have a component that only accepts props with specific types. However, Svelte doesn't directly assist with this, (unless you use TypeScript), so you have to figure out how to handle invalid props.

Describe the proposed solution

Add a rune for props that only accept certain types. These types would be both primitive types (string, number, object, etc), and classes. The rune would be used in a similar syntax as $bindable(), in the default values of the $props() declaration. If an invalid prop is used, Svelte could throw with an error code similar to invalid_prop_type. I have a few ideas for what this rune would be named and how the rune's syntax would work:

Possible names

  • $props.accepts()
  • $props.restrict()
  • $props.type()
  • $props.only()

Or it could be a standalone rune, which would mean cleaner code, but I don't know if it's important enough (not to mention it could look more confusing to new Svelte users):

  • $only()
  • $accepts()
  • $type()

Possible arguments syntax

  • An object with the primitive types accepted in a type/typeof property, and the class types in an instance/instanceof property (example: $props.only({typeof: ["string","number"], instanceof: Class}))
  • An array or multiple arguments with the constructors of the classes accepted and the primitive type names accepted (example: $props.accepts("string", "number", Class)

Full syntax example

<script>
let {onlyStringOrNumber = $props.type("string","number"), onlyClassInstance = $props.type(Class)} = $props();
</script>

Minor details

  • I'm not sure how a bindable prop that only accepts certain types would work. It might just be like wrapping the accepted types in a $bindable (example: prop = $bindable($props.accepts({typeof: "string"}))) or something else entirely
  • I'm not sure if there should be a way to control whether an invalid prop throws or warns. Throwing should be the default, but I don't know if there'd be a reason to have the ability to warn instead.
  • I'm not sure if this should also restrict whether the value can be reactive or not (eg: <Component prop={1}> is not reactive, but <Component prop={thing}> is reactive). If so, I'm also not sure if this would be a separate rune ($props.static/$props.reactive?) or just another part of the type restriction rune.

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions