Can someone provide an explanation of the Typescript peerDependencies in Angular, specifically comparing versions tslib 1.* and 2.3.*?

I am in the process of starting a new angular project, but I'm facing difficulties in importing the localStorage feature. I referred to an existing project that utilized localStorage in the following way:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthenticationService, LoginModel } from '../_libraries/card-system-core';

export class AuthenticationHelper {
//...
    constructor(private authService: AuthenticationService, private router: Router) {
        this.currentUserSubject = new BehaviorSubject<AuthInfo>(JSON.parse(localStorage.getItem(this.STORAGE_NAME)));
        this.currentUserRouteSubject = new BehaviorSubject<RouteInfo[]>(JSON.parse(localStorage.getItem(this.STORAGE_ROUTES_NAME)));

        this.currentUser = this.currentUserSubject.asObservable();
        this.currentUserRoute = this.currentUserRouteSubject.asObservable();
    }
//...

The old project was written in TypeScript, but when attempting to implement localStorage in my new project, I encountered the following error: https://i.sstatic.net/eMvxU.png

I was hoping that it would be linked properly to allow for "go to definition" functionality, as seen here: https://i.sstatic.net/Spp39.png

I discovered a line in the old project's package.json file under "peerDependencies":

  "dependencies": {
    "tslib": "1.10.0"
  },
  "devDependencies": {
    "ts-node": "~5.0.1",
    "tslint": "~6.1.0",
    "typescript": "~4.2.4"
  },
  "peerDependencies": {
    "tslib": "1.10.0"
  }

However, using "peerDependencies" with "tslib": "2.3.0" did not work in my new project. It only worked when I reverted to version 1.10.0 under "peerDependencies" in my project setup:

"dependencies": {
    "tslib": "^2.3.0",
},
"devDependencies": {
    "ts-node": "^10.9.1",
    "typescript": "~4.7.2"
}

So, my question is why was it necessary to specify "tslib": "1.10.0" in peerDependencies to make localStorage work? I'm unsure of the relationship between TypeScript, peerDependencies, and tslib. Is it not standard practice to use peerDependencies for "tslib": "2.3.0" when utilizing localStorage?

Eventually, I made changes to my code as follows. Thank you for your assistance:

        let storagedName = localStorage.getItem(this.STORAGE_NAME);
        let storagedRouteName = localStorage.getItem(this.STORAGE_ROUTES_NAME);

        let emptyUser:AuthInfo = {
            accessToken: "",
            routes: [],
            twoFA: false,
            forgotPassword: false,
            errorMessage: ""
        }
        this.currentUserSubject = new BehaviorSubject<AuthInfo>(emptyUser);
        if(storagedName)
            this.currentUserSubject = new BehaviorSubject<AuthInfo>(JSON.parse(storagedName));

        this.currentUserRouteSubject = new BehaviorSubject<RouteInfo[]>([]);
        if(storagedRouteName)
            this.currentUserRouteSubject = new BehaviorSubject<RouteInfo[]>(JSON.parse(storagedRouteName));

Answer №1

The issue does not lie in the package specified in the peerDependencies.

When you encounter the error message in VS Code, it will provide an explanation of the problem. The key used to fetch the value can either be a string or null. However, for localStorage, it must be a string.

You can attempt something similar to the following:

if(this.STORAGES_ROUTES_NAME) {
 localStorage.getItem(this.STORAGES_ROUTES_NAME)
}

If the variable cannot be null, then you will need to alter how the variable is declared.

Perhaps, the older version of tslib does not enforce variable types, which is why it is functioning correctly.

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

What is the best way to modify the nested state of a dynamically generated state with the useState hook?

I'm currently facing a challenge when trying to update a nested property of a useState object. Here's the specific scenario: In the component, there is a prop "order" that contains multiple items (line_items) which represent the products in th ...

Can a website be created to cater to all screen resolutions, from mobile devices to PCs?

Is it possible to create a website that is flexible and can stretch like elastic rubber, accommodating text, images, videos, JavaScript, and accessible from all web-enabled devices? I envision setting a maximum width of 980px for the site, allowing for a ...

Whenever attempting to choose a rating, the MUI dialog continuously refreshes and resets the selected rating

I'm facing an issue with my MUI dialog where it keeps refreshing and resetting the selected rating every time I try to rate a movie. Any assistance on this matter would be highly appreciated. The RateWatchMovieDialog component is designed to display ...

Guide to turning off the Facebook iframe page plugin

I am facing a challenge with embedding a facebook iframe on my website. I want to disable it once the screen width reaches a specific point, but I am struggling to make the iframe disappear properly. Here is how I have attempted to implement this: window.o ...

Tips for enhancing efficiency in a ionic application with over 100,000 items

My Ionic 4 app includes a page displaying a list of items ranging from 0 to 100,000. Unfortunately, when the list is loaded, the app's performance deteriorates and it closes unexpectedly. I am seeking a solution to enhance the loading and rendering p ...

Protractor and Jasmine fail to fulfill the promise of retrieving a webpage title

I am facing an issue with my protractor/jasmine test code where it only prints out 1 and 2, then hangs and times out. It seems like there might be a problem with the click() action on the button element or the promise on the getTitle method of the browser ...

Avoid Bootstrap 5 collapse when clicking on links or buttons

In my table, there are parent rows with hidden child rows that can be toggled using the bootstrap collapse feature. Clicking on a parent row toggles the visibility of its child rows. Both parent and child rows can be dynamically added to the table. Parent ...

Resetting the caret position in a React Native TextInput occurs when switching the secureTextEntry prop

As I develop a component to wrap the React Native TextInput in my app, I encounter an issue with the caret position resetting to 0 when toggling the secureTextEntry prop for password visibility. To address this problem, I implemented a workaround using a s ...

Error: Unable to access the currentTime property as it is not defined

Incorporating Videojs into my react application has presented a challenge. I am attempting to set the current time of the videojs player, but keep encountering an error that reads "cannot read property currentTime of undefined". Below is my approach: var ...

Attempting to create a fresh string by substituting certain characters with different ones

Exploring TypeScript, I encountered a puzzle where I needed to substitute specific characters in a string with other characters. Essentially, replacing A with T, T with A, C with G, and G with C. The initial code snippet provided to me looked like this: e ...

Using the .map function on JSON data with and without a parent element in JavaScript

In my current project, I am working on a React + Rails application. For handling JSON data, I typically use the default jbuilder in Rails. However, following the recommendations from the react-rails official documentation, I started adding a root node to m ...

How can I rearrange the output produced from a form by utilizing arrays?

The following code snippet generates the output: Apple,Orange Sliced,Diced Option1 Option2 Option3 Option4 ,Option1 Option2 Option3 Option4 Desired output: Apple Sliced Option1 Option2 Option3 Option4 Orange Diced Option1 Option2 Option ...

The Angular2 cli throws an error stating: "Cannot add a new entry to an existing one."

I have been utilizing the Angular2 Cli as my runtime environment for my Angular 2 application and I must say, I am thoroughly impressed by its architecture, top-notch development tools, and overall well-thought-out design. However, every so often, specifi ...

Using jQuery to fetch and display content from an external webpage

Is there a more effective method for loading an external web page on the same server? I've experimented with .load() and .get(), but they only load the page after the PHP script is finished. I've also used an iFrame, which displays the informatio ...

Initiating the node js service locally

I have been working on a Node.js and Gradle application, but I'm having trouble figuring out how to run it locally. So far, I've done the Gradle build (./gradlew) and NPM run build (compile), with all my dependencies neatly stored in the node_mo ...

Node.js data querying methods and best practices for code structuring

Recently delved into the world of nodejs and still fairly new to JavaScript. In my quest for best practices, I stumbled upon this helpful resource: Currently, I am working on an application following the structure recommended in the resource. The suggesti ...

I am experiencing some issues with the functionality of the Bootstrap carousel on my website's homepage

I've been working on creating an image carousel with Bootstrap 4, but I'm running into some issues. The images aren't sliding properly, and the cursor to change slides isn't functioning correctly. Additionally, the slides seem to repeat ...

Choosing between JavaScript and Handlebars.js depends on the specific needs

Can anyone explain the advantages of utilizing Handlebars.js or similar libraries over solely relying on JavaScript? Thus far, I haven't come across any functionality in Handlebars that cannot be achieved with just pure JavaScript. ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

Angular material mat-calendar multiyear range selection视图

Experiencing an issue with a mat-calendar multiyear view. By default, the dropdown multiyear table displays 3 years back and 20 years forward from the current year (2016, 2017....2030). https://i.sstatic.net/tWSif.png Instead, I am looking to view 23 yea ...