0

I am using ts and keep getting stuck when trying to create const that can be used by just changing a simple element.keep getting A class member cannot have the 'const' keyword

code:

const LINKS = {
  Summary: 82,
  Telephone: 83
};

itemLocator(ItemId): Locator {
  const navItemSelector = `'div[id="${ItemId}"]'`
  return page.locator(itemLocator)
}

tired doing const function, and const

philnash
  • 70,667
  • 10
  • 60
  • 88
dian
  • 19
  • 1
  • 1
    Right. A class member cannot have the `const` keyword. What's your question? – Robby Cornelissen Apr 05 '22 at 02:48
  • 1
    You can use readonly modifier instead. Look at this answer. https://stackoverflow.com/questions/37265275/how-to-implement-class-constants – Jay Bhatt Apr 05 '22 at 02:49
  • 1
    Does this answer your question? [How to implement class constants?](https://stackoverflow.com/questions/37265275/how-to-implement-class-constants) – Jay Bhatt Apr 05 '22 at 02:49
  • Please provide a [mre] that clearly demonstrates the issue you are facing. Ideally someone could paste the code into a standalone IDE like [The TypeScript Playground (link here!)](https://tsplay.dev/mLlRZm) and immediately get to work solving the problem without first needing to re-create it. So there should be no pseudocode, typos, unrelated errors, or undeclared types or values. – jcalz Apr 05 '22 at 02:53

1 Answers1

2

The duplicate answers that suggest using readonly in the comments are valid for simple properties.

In your case, because you're using an object property, you need an additional const assertion:

class Test {
  readonly LINKS = {
    Summary: 82,
    Telephone: 83
  } as const;
}

const test = new Test();
test.LINKS = {}; // error
test.LINKS.Summary = 83; // error

Without the const assertion, you would still be able to change the value Summary and Telephone values inside LINKS.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156