Attempting to update a variable within a function results in an error message stating: "Attempting to use block-scoped variable '...' before it has been declared.ts(2448)"

I'm currently working on a typescript function that takes in a numeric array (defined as type: number[]) and computes the mean. I want to make sure that the function can handle cases where the input array includes some null values. To address this, I introduced an additional parameter that, when set to true, instructs the function to eliminate any nulls before calculating the mean.

However, I'm struggling to find the right approach for this problem since I am unable to modify the original input array within the function.

This is the code snippet for my calcMean() function:

function calcMean(arr: number[], nullRemove: boolean = true): number {
    if (nullRemove) { // If 'true', which is the default value, remove nulls from the array
        const arr: number[] = arr.filter((elem) => elem !== null);
    }
    // Now proceed with calculating the mean of the modified `arr`
    return arr.reduce((acc, v, i, a) => acc + v / a.length, 0); // Reference: https://stackoverflow.com/a/62372003/6105259
}

Upon execution, I encounter the following error message:

Block-scoped variable 'arr' used before its declaration.ts(2448)

I attempted using let instead of or alongside const, but unfortunately, it did not resolve the issue.

Can someone guide me on what I might be overlooking here?

Answer №1

Here are two options for you:

1. Instead of redeclaring it, simply reassign it like this:

function calculateMean(numbers: number[], excludeNulls: boolean = true): number {
    if (excludeNulls) { 
        numbers = numbers.filter((element) => element !== null);
    }
    return numbers.reduce((accumulator, value) => accumulator + value / numbers.length, 0); 
}

Some argue that reassigning parameters is not a good practice, so here's an alternative approach:

2. Assign the filtered array to a different variable:

function calculateMean(numbers: number[], excludeNulls: boolean = true): number {
    const newArray = excludeNulls ? numbers.filter(element => element !== null) : numbers;
    return newArray.reduce((accumulator, value) => accumulator + value / newArray.length, 0);
}

Answer №2

The current code in your question does not handle null values within the number[] parameter.

I prefer my code to be explicit, so if there are any null values mixed in with the array of numbers, I would convert them to 0 explicitly instead of removing them:

/** Each null element is either omitted or converted to 0 */ function handleNullValues (arr: readonly (number | null)[], omit = true): number[] { return omit ? arr.filter((value): value is number => value !== null) : arr.map(value => value === null ? 0 : value); } function calcMean (arr: readonly (number | null)[], nullRemove = true): number { const numbers = handleNullValues(arr, nullRemove); return numbers.reduce((sum, n) => sum + n) / numbers.length; } // Test console.assert(calcMean([null, 1, 3, 7, 9]) === 5); // ok console.assert(calcMean([null, 10, 1, 3, 7, 9], false) === 5); // ok


Edit: Updated based on a comment you made.

TS Playground

function calcMean (arr: readonly (number | null)[]): number {
  let count = 0;
  return arr.filter((value): value is number => {
    const isNumber = typeof value === 'number';
    if (isNumber) count += 1;
    return isNumber;
  }).reduce((sum, n) => sum + n) / count;
}


// Test
console.assert(calcMean([1, 3, 7, 9]) === 5); // ok
console.assert(calcMean([null, 1, 3, 7, 9]) === 5); // ok

Answer №3

When working with typescript, I encountered the following error message:

Block-scoped variable 'filename' used before its declaration.ts(2448)

exportAsExcel () {
   const format = 'xlsx'
   const exportSelectedOnly = true
   const filename = 'test'
   this.$refs.grid.exportTable(format, exportSelectedOnly, filename)
}

To resolve this issue, I made the following changes:

const format = 'xlsx' as string
const exportSelectedOnly = true as boolean
const filename = 'test' as string

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

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

What is the method for initializing a Multidimensional Array of a specific size using Typescript?

Here is the code snippet... export class Puzzle { pieces : Piece[]; orderedPieces : Piece[][]; constructor(width: number, height: number){ this.height = height, this.width = width; let total : number = width * height; this.pieces = new A ...

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

Encountering a problem with updating values in local storage using ReactJS

My goal is to store values in local storage, but I am facing an issue where it saves an empty array in local storage the first time I click on Set Item. After the initial setup, the code works as expected. I am relatively new to React and TypeScript. Below ...

`Understanding the outcome type by assessing the (potential) attributes with TypeScript`

Here is a detailed example of a problem with some code: type Mapper<T, R> = (data: T) => R; interface Config<T, R> { readonly mapper?: Mapper<T, R>; } function transform<T, R>(config: Config<T, R>, data: T) { return c ...

Invoking functions using union types in Angular TypeScript

I have a challenge where I need to pass an Array<number|string> to a function that accepts Array<number|string> and returns either an Array<number> or an Array<string>. Unfortunately, the method overloading doesn't seem to be ...

Discovering a user's role in a WordPress site within an Angular application

I am currently in the process of integrating an Angular application into a WordPress theme. Certain Angular components need to verify if a user is logged in and has a specific role in order to display certain content. Since WordPress is built on PHP and An ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...

"An issue of type TypeError occurred: When logging out of the application, it appears that 'x is null

Currently in my app, I am working on implementing authentication following the guidance provided in this example: Click here for more information. However, I have encountered an error that reads "ERROR TypeError: 'x is null'" when trying to execu ...

Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so: enum AllDirections { TOP = 'top', BOTTOM = 'bottom', LEFT = 'left', RIGHT = 'right', } However, trying to use variab ...

Tips for adding Firebase 3 typings to a TypeScript 2 project installation

Running npm install @types/firebase --save-dev will actually install type definition files for version 2.4.30, not version 3. I suspect that the type definition files for version 3 may not be available through npm at this time. Can anyone confirm? It&apo ...

Guide to generating a fresh array of objects by combining values from two arrays!

I'm having difficulties combining two arrays of objects (retrieved from blockchain data) into a new array based on the values of the objects. The aim is to extract the most recent interaction with a user. A simplified yet closely resembling represen ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

Leveraging Typescript Definitions Files from Definitely Typed with an Outdated Typescript Version

I've been struggling with integrating third party React component libraries into my project that uses Typescript 1.8.10 along with React and Redux. Specifically, I've been attempting to use React Date Picker, but have encountered issues due to th ...

Having difficulty refreshing UI using React useState while trying to update an array of elements

Struggling with updating my UI using React and useState. Any help would be greatly appreciated. I am trying to remove an item that a user added. interface Links { link: string; } const [redirectLinks, setRedirectLinks] = useState<Links[]>([ { ...

Exploring how to utilize class properties within Angular templates

I am facing an issue with using a template property in Angular. Despite my attempts, it is not functioning as expected and I am unable to pinpoint the cause of the problem. To illustrate, I have set up a demonstration here: https://github.com/Fulkerson/an ...

Utilizing ES6 class methods as a parameter for Express routing

I'm having trouble passing a class method as an Express route parameter. I've attempted to bind the method and also tried using arrow functions, but neither approach has worked for me. My project involves TypeORM, and I keep encountering the err ...

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...