2

i am declaring a subscription in Angular like this:

counterSubscription: Subscription

and it is giving me this error:

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

So what could be the initial value of a Subscription please?

Gaël J
  • 11,274
  • 4
  • 17
  • 32
  • `undefined`? Or `null`? – Gaël J Aug 15 '21 at 10:39
  • put a semicolon in the end. it should give a error. – Aakash Garg Aug 15 '21 at 10:42
  • `counterSubscription!: Subscription;` you can use this and initialize subscription in ngOnInit(). I would recommend to use `counterSubscription = new Subscription();` directly instead of initialize it in ngOnInit(). This can reduce your code. – JsNgian Aug 16 '21 at 14:52

2 Answers2

3

If you are initializing your subscription in an angular lifecycle hook, like ngOnInit, you can use the Definite Assignment Assertion Operator ! to inform TypeScript that the variable will be initialized.

counterSubscription!: Subscription;
BizzyBob
  • 12,309
  • 4
  • 27
  • 51
2

You can also add strictPropertyInitialization: false rule to your tsconfig.json to disable this behaviour.

BunyamiN
  • 533
  • 4
  • 10