solid-router icon indicating copy to clipboard operation
solid-router copied to clipboard

Components consuming load functions no longer need non-null assertions

Open spiffytech opened this issue 1 year ago • 1 comments

Currently, load functions are clumsy to use from TypeScript because the RouteSectionProps type marks the data prop as optional. If you try working around that in your component (such as Component<Required<RouteSectionProps<MyProps>>>), you instead get compile errors that your component's props type isn't assignable to RouteDefinition.

The only workaround I've found is runtime null checks, or type-level non-null assertions, inside every component that uses load functions.

This PR marks the data prop as non-optional: the route props will always have a data field, set to the RouteSectionProps generic parameter type. If not load function is supplied, the field's value would be undefined, with a type of unknown.

What happens if the route doesn't have a load function defined? Your component would be declared as Component<RouteSectionProps>. Without the type param supplied, the data prop receives type unknown, and is unusable inside your component.

If a component sometimes does/doesn't receive load data, it can use Component<RouteSectionProps<Foo | undefined>>.

This approach provides accurate types when you have a load function, and still signals the data prop cannot be read when you do not have a load function.

spiffytech avatar May 17 '24 00:05 spiffytech

⚠️ No Changeset found

Latest commit: e963ad3a0bd414d0788801ba853b3d395237a438

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

changeset-bot[bot] avatar May 17 '24 00:05 changeset-bot[bot]