Home > Back-end >  Make typescript aware that a function initializes a field
Make typescript aware that a function initializes a field

Time:09-02

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)

CodePudding user response:

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'
 }
}

CodePudding user response:

I think there are only 2 ways of doing it.

One is that you already mentioned with Definite assignment assertion and the second is to change the TS config and set noImplicitAny to false.

But if the assignment is not happening in the constructor explicitly or the property does not have a default value it will always complain.

If the whole point of this question is to avoid duplication of properties in the class body and in the constructor you can try passing access modifiers directly inside constructor parameters

class MyClass {
  constructor(private foo: string, private bar: string){}
}

This is the equivalent of the code below

class MyClass {
  private foo: string;
  private bar: string;

  constructor(foo: string, bar: string){
    this.foo = foo;
    this.bar = bar;
  }
}
  • Related