At first, I encountered the following errors:
server.ts:30:12 - error TS2339: Property 'shop' does not exist on type 'Session | null'.
30 const {shop, accessToken} = ctx.session;
~~~~
server.ts:30:18 - error TS2339: Property 'accessToken' does not exist on type 'Session | null'.
30 const {shop, accessToken} = ctx.session;
~~~~~~~~~~~
Upon adding
const {shop, accessToken} = ctx.session as {shop: string, accessToken: string}
, the error message changed to the following:
server.ts:48:31 - error TS2352: Conversion of type 'Session | null' to type '{ shop: string; accessToken: string; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'Session' is missing the following properties from type '{ shop: string; accessToken: string; }': shop, accessToken
48 const {shop, accessToken} = ctx.session as {shop: string, accessToken: string};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[4:52:59 AM] Found 4 errors. Watching for file changes.
I am new to Typescript and considering two options:
- Modify the line to
const {shop, accessToken} = ctx.session as unknown as {shop: string, accessToken: string}
- Create an interface for
Session
and assert ctx.session to it (ctx.session as Session
), replacing the previous type assignment (Session|null).
Does this approach seem correct? Which option would be more preferable in this scenario?