Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make typescript aware that a function initializes a field

Tags:

typescript

I have the following class declared:

class MyClass {
 private myValue!: string

 constructor(){
   this.mySettingFunction()
 }

 public mySettingFunction(){
   // do stuff
   this.myValue = 'something'
 }
}

In this class, I'm using the definite assignment assertion(!) on myValue to tell typescript that the value will be initialized despite it not being able to "understand" it.

However, I was guessing, is there a way to tell typescript that mySettingFunction will initialize myValue? (Like an annotation or something similar that allows me to remove the ! from myValue)

like image 805
Andrea Costanzo Avatar asked Dec 21 '25 20:12

Andrea Costanzo


1 Answers

What about these two options?

1.

class MyClass {
 private myValue: string | undefined = undefined;

 constructor(){
   this.mySettingFunction();
 }

 public mySettingFunction(){
   // do stuff
   this.myValue = 'something';
 }
}
class MyClass {
 private myValue = '';

 constructor(){
   this.mySettingFunction()
 }

 public mySettingFunction(){
   // do stuff
   this.myValue = 'something'
 }
}
like image 132
Robert Rendell Avatar answered Dec 23 '25 13:12

Robert Rendell



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!