-2

I'm using angular framework and here is my class structure:

export class Demo {
  _name: string;

  constructor(inputName: string) {
    this.name = inputName;
  }

  public set name(inputName: string) {
    this._name = `%${inputName}%`;
  }

  public get name(): string {
    return this._name;
  }
}

And it give me an error:

Property '_name' has no initializer and is not definitely assigned in the constructor.

How can I prevent it?

Suspended
  • 169
  • 2
  • 11
  • 1
    Fix the variable name in the constructor. – R. Richards Jul 07 '22 at 12:25
  • @R.Richards I have some processing in the setter, if i just set the value to _name directly, It will bypass the processing. – Suspended Jul 07 '22 at 12:33
  • 1
    Just Googled your error, and it seems like your question is [a duplicate](https://stackoverflow.com/a/49699097/19330634). Please DYOR – l -_- l Jul 07 '22 at 12:36
  • @l-_-l Nope. I'm not attempt to declare a porperty without initialize. I'm asking how can I initialize a property through a setter in the constructor. – Suspended Jul 07 '22 at 12:45

1 Answers1

0

You have several options

Option 1:

use ! to tell TypeScript's Strict Class Initialization that it's OK not to initialize _name

_name!: string;
  // ^
  // Notice this '!' modifier.
  // This is the "definite assignment assertion"

Option 2:

Set _name in the constructor "correctly"

  constructor(inputName: string) {
    this._name = inputName; // _name, not name
  }

Option 3:

Initialize _name to a default string value. This will ensure that the _name is never something other than a string. If you don't set it, _name can be undefined.

_name: string = '';
John
  • 10,165
  • 5
  • 55
  • 71
  • Option 1 did fix the error , just a little bit wire because I already initialize it through the setter. So does it mean I have to initialize the property directly in the constructor? – Suspended Jul 07 '22 at 12:59
  • That’s not your only option, but I don’t think you can do it through a function (setter) in the constructor. You need to do any of the options I described, or take a look at this https://stackoverflow.com/a/49699097/19330634 – John Jul 07 '22 at 22:56