Redeclaring block-scoped variable 'reducer' is not allowed in TypeScript

I encountered an error message

Cannot redeclare block-scoped variable 'reducer'
when running sample code from a book using tsc. I'm unsure of the reason behind this issue.

tsc -v 
// Version 2.1.0-dev.20160726

Next, I executed ts-node in the following manner:

ts-node 01-identity-reducer.ts

In file 01-identify-reducer.ts:

interface Action {
  type: string;
  payload?: any;
}

interface Reducer<T> {
  (state: T, action: Action): T;
}

let reducer: Reducer<number> = (state: number, action: Action) => {
  return state;
};

console.log( reducer(0, null) ); // should output -> 0

ERROR

    TSError: ⨯ Unable to compile TypeScript
01-identity-reducer.ts (10,5): Cannot redeclare block-scoped variable 'reducer'. (2451)
    at getOutput (/Users/person/.nvm/versions/node/v5.0.0/lib/node_modules/ts-node/src/index.ts:258:17)
    at /Users/person/.nvm/versions/node/v5.0.0/lib/node_modules/ts-node/src/index.ts:267:16
    at Object.compile (/Users/person/.nvm/versions/node/v5.0.0/lib/node_modules/ts-node/src/index.ts:403:17)
    at loader (/Users/person/.nvm/versions/node/v5.0.0/lib/node_modules/ts-node/src/index.ts:289:33)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/person/.nvm/versions/node/v5.0.0/lib/node_modules/ts-node/src/index.ts:306:14)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:457:10)
    at Object.<anonymous> (/Users/person/.nvm/versions/node/v5.0.0/lib/node_modules/ts-node/src/_bin.ts:179:12)
    at Module._compile (module.js:425:26)

Answer №1

Encountered an issue with redeclaring block-scoped variable 'reducer' in TypeScript compilation, perplexed by the cause

If your file lacks a root level import or export, it falls under the category of a global module. It appears that another global module also declares the variable reducer.

Solution

Transition to modules (consider commonjs). As an alternative, switch from let to var, this should prompt an error where another reducer is declared.

PS: An IDE can greatly enhance this experience by pinpointing other variable declarations upfront.

Answer №2

To encapsulate it, simply export a namespace.

export namespace YourPreference { ...code... }

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

Guide to making a personalized decorator in loopback4

async verifyUserMembership(userId: string, productId: string) { if (userId && productId) { const userExists = await Product.find({ where: { userId: userId, id: productId } }); return !!userExists; } return false; } I am ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Error: Angular encountered an unexpected token in the syntax

I am encountering an issue while trying to incorporate a user's profile updater on my website. Whenever I attempt to access a user's profile on the site, I run into this Angular error: main.ts:6 ERROR SyntaxError: Unexpected token 'e', ...

Challenge with Dependency Injection in the Handlers of NestJS CQRS repositories

As a newcomer to nodejs, I am currently delving into the implementation of NestJS's CQRS 'recipe'. In my service, I have a Request scoped with the injection of QueryBus: @Injectable({scope: Scope.REQUEST}) export class CustomerService { co ...

Make sure to wait for the store to finish updating the data before accessing it. Utilize RxJS and Angular

Greetings! I am currently working with Angular and RxJS, and I'm trying to find a solution to wait for the store's data to be updated after an action is dispatched in order to perform some operations using that data. Below you can see a snippet o ...

Leverage the power of zustand actions in your axios queries!

In my React application, I have implemented Zustand for creating a store: import { create } from 'zustand'; interface IAuth { username: string; isAuthentificated: boolean; updateAuth: (isAuth: boolean) => void; } export const useAuth = ...

Angular model-based forms encounter an issue with converting null to an object during asynchronous validation

In my Angular app, I'm working on implementing async validation for a model-based form. I've simplified the form by removing other fields for clarity, but there are additional fields in the actual form. The goal is to check if a username is uniqu ...

how can one exhibit the value of an object in TypeScript

Does anyone know how to properly display object values in forms using Angular? I can see the object and its values fine in the browser developer tools, but I'm having trouble populating the form with these values. In my *.ts file: console.log(this.pr ...

Here is a guide on implementing Hash in URLs with React Router

I'm brand new to React and running into an issue. My page has two tabs and I would like to create a hash URL that will redirect to the corresponding tab based on the URL hash. Additionally, when I change tabs, I want the URL to update as well. Please ...

Tips for sending a query using the http GET method in Next.JS 14 API routes

When using the Next.js 14 API route, I am passing a page in the GET method to paginate the data fetched from my database. However, an error is thrown when trying to retrieve the query from the request: Property 'query' does not exist on type &a ...

Dynamically load a custom element with a Component

I am attempting to dynamically inject a component into a container. Component: @Component({...}) export class InvestmentProcess{ @ViewChild('container') container; constructor(public dcl: DynamicComponentLoader) {} loadComponent(fo ...

Capable of retrieving information from an API, yet unable to display it accurately within the table structure

I'm currently working with Angular version 13.2.6 and a .NET Core API. I have two components, PaymentdetailsView (parent) and PaymentDetailsForm (child). Within the PaymentDetailsForm component, there is a form that, when submitted, makes a call to ...

Exploring the World of ES6 Modules, VueJS, and TypeScript

In my pursuit of creating a simplistic setup, I aim to incorporate the features mentioned above. In the realm of JavaScript code, below snippet plays a crucial role: <script type="module" src="./myapp.js"></script> This script is responsible ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

Updating Angular 5 Views Dynamically Using a While Loop

I am facing an issue in my app where I have a progress bar that updates using a while loop. The problem is that the view only updates after the entire while loop has finished running, even though I am successfully changing the update progress value with ea ...

Creating a mock instance of a class and a function within that class using Jest

I am currently testing a class called ToTest.ts, which creates an instance of another class named Irrelevant.ts and calls a method on it called doSomething. // ToTest.ts const irrelevant = new Irrelevant(); export default class ToTest { // ... some impl ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

Is it possible to execute TestCafe tests using TypeScript page objects that have not been utilized?

While working with TestCafe, I am implementing tests using the Page Objects pattern. I have already written some page objects in advance, even before their actual usage, as I am familiar with the page and know what to anticipate. However, when attempting ...

Proven method for transforming an Object containing a Map into a JSON Object

Is there a way to convert an object containing a map to JSON without losing the map data? When I use JSON.stringify(), the map data gets cleared. How can I solve this issue? frieghtChargesJSon:string; //declared variable frieghtChargesJSon=JSON.stringify ...

What To Do When You See "Unable to retrieve the 'get' property of an undefined or null reference" Error

I've encountered an error while trying to develop an application. The error message reads "Unable to get property 'get' of undefined or null reference at ProfilePage.prototype.ngOnInit". My framework of choice is Ionic 4. This error specif ...