Warning TS2352: There could be a potential mistake in converting a type 'Session | null' to type '{ x: string; y: string; }'

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:

  1. Modify the line to
    const {shop, accessToken} = ctx.session as unknown as {shop: string, accessToken: string}
  2. 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?

Answer №1

The issue arises when the variable "session" is potentially null, and since a null value does not have any properties.

You can try one of the following solutions:

const {store, token} = context.session!;

Alternatively:

if (context.session === null) { return; } // Alternatively, throw an exception or call next()
const {store, token} = context.session;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Ways to get into the Directive class

@Directive({ selector: '[myHighlight]' }) export class HighlightDirective { static test: number = 5; constructor(private el: ElementRef) { } highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } } In re ...

Sign up for a feature that provides an observable exclusively within an if statement

There is an if clause in my code that checks for the presence of the cordova object in the window global object. If cordova is present, it will make a http request and return the default angular 2 http observable. If the application is in a web context wh ...

Typescript error: Cannot assign type to argument

Exploring the world of typescript (2.5.2) and looking for clarity on why the first call works but the second one encounters an error: function printPerson(person: {firstName: string; lastName: string}): void{ console.log(person.firstName + " " + per ...

Bringing in a JSON file into a ReactXP project

I'm encountering a strange issue, possibly a bug, with importing a JSON file as an object into my application. I have the following configurations: "compilerOptions": { "resolveJsonModule": true, "esModuleInterop": true, } While it appears t ...

Navigating through a typescript array containing various types and mapping each element

Is there a way to get [valueOfTypeOne, ValueOfTypeTwo] instead of (valueOfTypeOne | ValueOfTypeTwo)[] for each resulting element in this scenario? const [valueOfTypeOne, ValueOfTypeTwo] = await Promise.all( [ fetchTypeOne(), fetchTypeTwo( ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Tips for Using Typescript Instance Fields to Prevent Undefined Values

After creating a few Typescript classes, I encountered an issue where I would get an undefined error when trying to use them after instantiating. I experimented with initializing my fields in the constructor, which resolved the problem, but I don't t ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...

When working with the "agora-rtc-sdk-ng" package, an error may be thrown by Next.js stating that "window is not defined"

Currently, I am in the process of incorporating the "agora-rtc-sdk-ng" package for live streaming with next.js and typescript. import AgoraRTC from 'agora-rtc-sdk-ng'; However, when I try to import it, an error is thrown as shown below: https:/ ...

Issue with Angular project: View not being updated when using behaviorSubjects

Within my Angular project, I am retrieving data from an API using a service and storing the data within a BehaviorSubject as shown below private categorySubject = new BehaviorSubject<number | null>(null); apiBehavior = new ReplaySubject<ApiRes ...

Error: Parsing error - Unrecognized character "@" in Angular module

Currently I am delving into the realm of webpack and attempting to integrate it into my project. However, I seem to have hit a roadblock as I encounter the following error. Despite my efforts to troubleshoot and research, I cannot seem to find a loader spe ...

Apply a spread of nested elements onto another spread

I am working with an array containing last names of Persons and need to populate new entries. However, I only have the last names and not the full Person objects. How can I address this issue? type Person = { name: string, lastName: string, age: ...

Excluding properties based on type in Typescript using the Omit or Exclude utility types

I am looking to create a new type that selectively inherits properties from a parent type based on the data types of those properties. For instance, I aim to define a Post type that comprises only string values. type Post = { id: string; title: string ...

Troubleshooting TypeScript: Issues with Object.assign and inheritance

After successfully using the code within an Angular project, I decided to switch to React only to find that the code is now producing unexpected results. class A { constructor(...parts: Partial<A>[]) { Object.assign(this, ...parts); } } cla ...

Utilizing the URL path name for data retrieval in Next.js 14 - A step-by-step guide

I'm currently developing a blog using AWS Amplify Gen 2 and GraphQL for a Next.js 14 project with TypeScript. As part of my application, I need to fetch specific data based on the URL path name. Here's how I've approached it: My approach in ...

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

Is it feasible to deduce the generic type of a function by considering all remaining arguments?

I'm working with code that looks like this: type Boxed<T> = { inner: T } const box = <T>(inner: T): Boxed<T> => ({ inner }); function test<T extends Boxed<any>>(...args: T[]): T extends Boxed<infer I> ? I : ne ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...