Sean D
Sean D

Reputation: 4292

error TS2352: Conversion of type 'Session | null' to type '{ x: string; y: string; }' may be a mistake

Initially I got these 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;
                    ~~~~~~~~~~~

After writing const {shop, accessToken} = ctx.session as {shop: string, accessToken: string} I am seeing 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 but believe I have 2 options

  1. Rewrite the line to const {shop, accessToken} = ctx.session as unknown as {shop: string, accessToken: string}
  2. Write an interface for Session and assert ctx.session to it (ctx.session as Session), overwriting the previous type assignment (Session|null).

Is this correct? What is the better choice here?

Upvotes: 0

Views: 3192

Answers (1)

Shalom Peles
Shalom Peles

Reputation: 2632

The problem is that "session" can be null, and null doesn't contain any property.

Try one of these:

const {shop, accessToken} = ctx.session!;

Or:

if (ctx.session === null) { return; } // Or throw, or next()
const {shop, accessToken} = ctx.session;

Upvotes: 1

Related Questions