Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an object variable, Error: **'const' declarations must be initialized.**

I am trying to initialize an object and assigned a value to that object but I seem to be getting an error when I declare the object.

Error: 'const' declarations must be initialized.

How do I initialize my object?

Code:

// Object
export type DateRange = {
  date: string;
};

const dateYears = (values: any) => {
  if (Array.isArray(values.dateYears)) {

    const dateRange: DateRange; // error
    values.dateYears.map((item: any) => {
      dateRange.createdDate = item.value;
    });
  }
};
like image 365
mig_08 Avatar asked Jun 15 '26 13:06

mig_08


1 Answers

From MDN Docs

An initializer for a constant is required. You must specify its value in the same statement in which it's declared. (This makes sense, given that it can't be changed later.)

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

So, You cant just initialize a const variable. You have to define it with some value,

const dateRange: DateRange = {};
like image 58
aeXuser264 Avatar answered Jun 17 '26 04:06

aeXuser264



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!