SvelteKit 2 redirects and data types #11372
-
Working on migrating to sveltekit 2, and trying to understand the change in redirects that previously were thrown, and now are just function calls. With the previous code, because the code was thrown, i could use it for type safety purposes in the returned data. Heres an example of what I could do:
Now any page using this load function would have a property in data that contained the user object (of type With sveltekit 2 it now looks like this
While at runtime it does the exact same thing (redirects if theres no user in session data), but the type returned to the page is now So it leaves me with 3 ideas for how to solve this |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Are you sure? I just tested this locally and it works perfectly. |
Beta Was this translation helpful? Give feedback.
-
hi Thank you for your insights! You are correct in your assessment regarding the behavior of the redirect function and the type narrowing that occurs in TypeScript. When the redirect function is invoked, it indeed returns never, which allows TypeScript to infer that the subsequent code will not execute in that branch. As a result, it is unnecessary to use optional chaining (data.session?.user) when accessing data.session.user, since TypeScript can confidently determine that data.session is defined in the context where the redirect function is not called. This leads to a more concise and clear codebase. Even if optional chaining is retained for safety, TypeScript's type inference is robust enough to recognize that the load function will always return a user of type User when the redirect condition is not met. This demonstrates the power of TypeScript's type system in ensuring type safety while also allowing for cleaner code. Thank you for bringing this to attention, and I appreciate the opportunity to clarify this aspect of TypeScript's behavior! |
Beta Was this translation helpful? Give feedback.
Are you sure? I just tested this locally and it works perfectly.
redirect
returnsnever
, which narrows the type. You don't need the seconddata.session?.user
, you can just dodata.session.user
, but even if you do leave in the optional chaining TypeScript is smart enough to know that theload
function always returnsuser: User