Skip to content

Svelte 5: Allow returning (object) $state directly? #12286

Closed
@brunnerh

Description

@brunnerh

Describe the problem

I have often run into a pattern where utility functions creating a stateful object create the object and immediately return it.
This is currently required as $state is only allowed in variable/ class field declarations.

E.g.

export function createSelection() {
	const selection = $state({
		items: [],
		isSelected(item) {
			return this.items.includes(item);
		},
		toggle(item) {
			this.items = this.items.includes(item)
				? this.items.filter(x => x != item)
				: [...this.items, item];
		},
	});

	return selection;
}

Describe the proposed solution

Allow return $state(), but maybe only if used with an object literal so problems like usage with primitives are caught more easily.

Importance

nice to have

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