8

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;
    });
  }
};
1
  • 1
    const dateRange: DateRange = {createdDate: ''}; and also change the interface Commented Oct 20, 2020 at 10:38

1 Answer 1

14

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 = {};
Sign up to request clarification or add additional context in comments.

1 Comment

@mig_08 pls mark as answer & upvote if it helped. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.