Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet:

import * as appSettings from 'application-settings';

try {
    //  shim the 'localStorage' API with application settings module 
    global.localStorage = {
        getItem(key: string) {
            return appSettings.getString(key);
        },
        setItem(key: string, value: string) {
            return appSettings.setString(key, value); 
        }
    }

    application.start({ moduleName: 'main-page' });
}
catch (err) {
    console.log(err);
}

I'm getting an error in VSCode that says

[ts] Property 'localStorage' does not exist on type 'Global'. [2339]
. Any suggestions on how to resolve this issue?

This code is for a Nativescript app. You can view the entire file/app here for reference: https://github.com/burkeholland/nativescript-todo/blob/master/app/app.ts

Answer №1

When using TypeScript, it's common to encounter issues with the global typings not including localStorage, resulting in it being flagged as an invalid property.

To resolve this error, you can simply cast it to any:

(<any>global).localStorage = {
    getItem(key: string) {
        return appSettings.getString(key);
    },
    setItem(key: string, value: string) {
        return appSettings.setString(key, value); 
    }
}

Alternatively, you have the option to extend the global typings from references.d.ts, typically found in your project root directory. If it doesn't exist, you can create one yourself:

declare namespace NodeJS {
    interface Global {
        localStorage: { getItem: (key: string) => any; setItem: (key: string, value: string) => any; };
    }
}

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

Stopping the subscription to an observable within the component while adjusting parameters dynamically

FILTER SERVICE - implementation for basic data filtering using observables import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { Filter } from '../../models/filter.model'; imp ...

Angular2, multi-functional overlay element that can be integrated with all components throughout the application

These are the two components I have: overlay @Component({ selector: 'overlay', template: '<div class="check"><ng-content></ng-content></div>' }) export class Overlay { save(params) { //bunch ...

Creating an object instance in Angular 2 using TypeScript

Looking for guidance on creating a new instance in TypeScript. I seem to have everything set up correctly, but encountering an issue. export class User implements IUser { public id: number; public username: string; public firstname: string; ...

What is the syntax for typing the router instance in Next.js?

I'm working on a password reset request form in my Next.js project. Here's the code I have: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } fro ...

Steps for reinstalling TypeScript

I had installed TypeScript through npm a while back Initially, it was working fine but turned out to be outdated Trying to upgrade it with npm ended up breaking everything. Is there any way to do a fresh installation? Here are the steps I took: Philip Sm ...

Arrangement of items in Angular 2 array

Received a JSON response structured like this JSON response "Terms": [ { "Help": "Terms", "EventType": "Success", "Srno": 1, "Heading": "Discount Condition", "T ...

What is the best way to synchronize API definitions between the server and client using TypeScript?

My setup involves a server (TypeScript, NestJS) and a client (TypeScript, Angular) that communicate with each other. Right now, I have the API response DTO classes defined in both the server to output data and in the client to decode the responses into a ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

Filter multiple columns in an Angular custom table with a unique filterPredicate

Looking to develop a versatile table that accepts tableColumns and dataSource as @Input(). I want the ability to add custom filtering for each table column. Currently, I've set up the initialization of the table FormGroup and retrieving its value for ...

Exploring Angular2's DOMContentLoaded Event and Lifecycle Hook

Currently, I am utilizing Angular 2 (TS) and in need of some assistance: constructor(public element:ElementRef){} ngOnInit(){ this.DOMready() } DOMready() { if (this.element) { let testPosition = this.elemen ...

The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables: NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own> MAGIC_SECRET_KEY=sk_test_<get-your-own> TOKEN_SECRET=some-secret These variables are printed out in the file ...

Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function? <div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div> The doubleClick function will ret ...

Tips on implementing npm's node-uuid package with TypeScript

Whenever I attempt to utilize node-uuid in TypeScript, I encounter the following issue: Cannot find module uuid This error occurs when I try to import the uuid npm package. Is there a way to successfully import the npm uuid package without encountering ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

How can data be transferred between controllers in Angular 2 without using URL parameters or the $state.go() function?

I've encountered an issue where I need to pass a parameter from one controller to another without it being visible in the URL. I attempted to do so with the following code: this.router.navigate(['/collections/'+this.name], {id: this.id}); ...

Creating a sidebar in Jupyter Lab for enhanced development features

Hi there! Recently, I've been working on putting together a custom sidebar. During my research, I stumbled upon the code snippet below which supposedly helps in creating a simple sidebar. Unfortunately, I am facing some issues with it and would greatl ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

What is the best way to display the arrows on a sorted table based on the sorting order in Angular?

I need assistance with sorting a table either from largest to smallest or alphabetically. Here is the HTML code of the section I'm trying to sort: <tr> <th scope="col" [appSort]="dataList" data-order ...