solidjs / solid-router

A universal router for Solid inspired by Ember and React Router
MIT License
1.1k stars 137 forks source link

Components consuming load functions no longer need non-null assertions #419

Closed spiffytech closed 1 month ago

spiffytech commented 1 month ago

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, at every call site that touches the data prop inside a component.

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.

changeset-bot[bot] commented 1 month ago

⚠️ 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