Svelte 18 ๐งก Component Props Declaration using $props()
The shift to Svelte 5 introduced a fundamental change in how components receive data from their parents. Historically, Svelte relied on the export let syntax, a pattern that, while simple, obscured the component’s internal interface and relied on compiler magic. The $props() rune replaces this mechanism, providing an explicit, type-safe, and highly readable way to declare component inputs. This rune acts as the contract between a parent and child component, defining exactly what data is expected and how it should behave within the componentโs reactive scope.
This chapter examines the shift from legacy prop declaration to the modern $props() approach. It details how to destructure props, apply default values, leverage TypeScript for interface enforcement, and handle rest parameters for flexible component composition. By the end of this chapter, you will understand how $props() consolidates component inputs into a single, centralized definition that improves maintainability and clear communication of intent in complex applications.
Key point: $props() is the definitive way to declare inputs in Svelte 5; it returns a reactive object containing all passed parameters, allowing for destructuring, default values, and strict TypeScript integration in one declarative step.
Why $props() exists
The legacy syntax ambiguity. The export let syntax was easy to use but conceptually confusing, as it borrowed a keyword from module management to define UI inputs. It lacked a central definition, making it difficult to visualize the entire component interface at a glance.
The explicit contract requirement. By centralizing prop declarations into a single $props() call, components now have a clear “top-of-file” interface. This improves readability for developers joining a project who need to see immediately what data a component requires to function.
TypeScript integration. $props() is designed to work seamlessly with TypeScript generics and interfaces. Instead of relying on compiler inference, you can explicitly type the entire props object, ensuring that the parent component provides the exact structure the child expects.
Reactivity consistency. In previous versions, distinguishing between a static prop and a reactive state variable was sometimes subtle. $props() provides a uniform way to handle data that comes from the outside, distinguishing it clearly from internal state created via $state().
The rest parameter necessity. Handling “passthrough” propsโdata meant for nested elements rather than the component itselfโwas previously messy. $props() makes it trivial to spread remaining properties, enabling the creation of wrapper components that inherit full attribute sets.
a. Basic declaration and destructuring
When you call $props(), it returns a reactive object representing all attributes passed to the component. You typically assign this result to a constant and then destructure the values you need. This pattern keeps the component interface clean and prevents “prop pollution” where every variable is prefixed with the export keyword.
let { title, count } = $props();
// Inside the template
<h1>{title}</h1>
<p>Count: {count}</p>
The key behavior here is that these variables are reactive. If the parent component changes the values passed to title or count, the child component will reactively update. Because this object is returned by the rune, Svelte tracks access to these specific properties, ensuring that the component only re-renders when the props it actually uses are changed.
b. Default values and strict types
Providing default values for props is now handled via standard JavaScript destructuring defaults. This eliminates the need for complex export let x = defaultValue logic dispersed throughout the file. By combining this with TypeScript, you can enforce strict schemas that prevent the component from running in an invalid state.
// Define a shape for the props
interface Props {
title: string;
count?: number; // Optional
}
// Destructure with default value
let { title, count = 0 }: Props = $props();
This approach is superior because the entire interface is defined in a single block. If a mandatory prop is missing from the parent, TypeScript will flag the error immediately. Furthermore, since the destructuring happens at the entry point of the component, there is no risk of the component logic accessing a prop that hasn’t been initialized yet.
c. The rest pattern and spreading
One of the most powerful features of $props() is the ability to use the rest syntax (...) to capture “extra” properties. This is vital for components that act as proxies for standard HTML elements, allowing you to pass down aria attributes, custom data attributes, or event listeners without explicitly defining every single one in your interface.
let { children, ...rest } = $props();
// Spread the rest props onto a div
<div {...rest}>
{children}
</div>
By capturing the remaining props in a variable (commonly named rest), you gain the ability to pass those props directly to nested components or elements. This is the idiomatic way to handle “pass-through” attributes in Svelte 5, significantly reducing the amount of manual prop-drilling required in your codebase.
Complete Example Session
// ============================================
// PART 1: INTERFACE DEFINITION
// ============================================
interface ButtonProps {
label: string;
variant?: 'primary' | 'secondary';
onclick: () => void;
[key: string]: any; // Allow arbitrary attributes
}
// ============================================
// PART 2: PROPS DECLARATION
// ============================================
let {
label,
variant = 'primary',
onclick,
...attributes
}: ButtonProps = $props();
// ============================================
// PART 3: TEMPLATE USAGE
// ============================================
// We apply the variant class and the extra attributes
<button
class="btn-{variant}"
onclick={onclick}
{...attributes}
>
{label}
</button>
This session shows the end-to-end flow: defining a type interface, capturing props with the $props() rune, providing a default value, handling rest attributes for extensibility, and applying everything to the component template.
Quick Reference
Prop Patterns
| Pattern | Syntax | Description |
|---|---|---|
| Basic | let { a } = $props() | Extracting a prop |
| Default | let { a = 1 } = $props() | Setting default values |
| Rest | let { ...r } = $props() | Capturing unused props |
| Aliasing | let { a: alias } = $props() | Renaming a prop |
Type Enforcement
| Method | Syntax | Use Case |
|---|---|---|
| TS Interface | let p: Props = $props() | Strong typing |
| Optional | prop?: type | Making props optional |
| Union Types | variant: 'a' | 'b' | Strict selection |
Best Practices
โ Do This:
// Define interfaces at the top
interface Props { val: string; } // โ
// Always provide defaults for optional props
let { color = 'red' } = $props(); // โ
// Use rest for pass-through attributes
let { children, ...rest } = $props(); // โ
โ Don’t Do This:
// Don't use legacy export let
export let name = 'default'; // โ
// Don't mutate props directly
$props().value = 1; // โ
// Don't define props in the middle of logic
// (keep it at the top) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Prop Mutation | Attempting to change a prop | Use internal state copy |
| Missing Type | Forgetting to assign interface | Assign to $props() |
| Name Clash | Overlapping local var names | Use aliasing { p: myProp } |
| Rest Overwrite | Spreading attributes after static | Spread before explicit props |
Real-World Examples
1. Basic string prop
let { name } = $props();
2. Number with default
let { limit = 10 } = $props();
3. Handling children
let { children } = $props();
4. Event handler prop
let { onchange } = $props();
5. Rest attributes for div wrapper
let { ...rest } = $props();
<div {...rest}>...</div>
6. Required boolean
let { active }: { active: boolean } = $props();
7. Prop aliasing
let { title: header } = $props();
8. Complex object prop
let { config }: { config: ConfigObj } = $props();
9. Optional array
let { items = [] } = $props();
10. CSS variable passing
let { '--color': color } = $props();
Visual
Data Flow Model
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PARENT COMPONENT โ
โ <Child title="Hello" count={5} /> โ
โ โ โ
โ โผ โ
โ CHILD COMPONENT โ
โ let { title, count } = $props(); โ
โ โ โ
โ โผ โ
โ TEMPLATE (Uses reactive title/count) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Inheritance via Rest Props
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INCOMING PROPS โ
โ { id: '1', class: 'btn', type: 'submit' } โ
โ โ โ
โ let { ...rest } = $props(); โ
โ โ โ
โ <button {...rest}> โ
โ (Button inherits all three props) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Interface Contract
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INTERFACE DEFINITION โ
โ interface ButtonProps { โ
โ label: string; โ
โ variant?: string; โ
โ } โ
โ โ โ
โ $props() ASSIGNMENT โ
โ let props: ButtonProps = $props(); โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Rune | $props() |
| Scope | Component Input |
| Syntax | Destructuring |
| TypeScript | Supported via interface |
| Rest | Via ...rest |
Key takeaways:
- Centralize interfaces. Use
$props()at the top of your component to define all external inputs clearly, moving away from fragmentedexport letdeclarations. - Enforce with TypeScript. Always annotate your
$props()with an interface to ensure that the component contract is enforced during development. - Defaulting is built-in. Use standard JavaScript destructuring defaults to handle missing or optional props, which simplifies the logic inside the component.
- Passthrough is idiomatic. Use the rest spread operator
...restto capture and forward attributes, which is the standard way to create flexible, high-order components. - Treat props as immutable. Props received via
$props()should be treated as read-only. If you need local changes, initialize a separate$state()variable with the prop value.
Remember: The $props() rune is the modern, robust successor to export let. It turns your component inputs from hidden, implicit side effects into an explicit, typed, and easily discoverable interface. By adopting this pattern, you ensure that your Svelte 5 components are cleaner, more predictable, and easier to debug, as every piece of data flowing into a component is explicitly accounted for in a single, well-defined location.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!