1

I am trying to do some if/else statements in a TypeScript program in an Angular webpage that I am developing. Here is a reproducible case:

export class AppComponent {
  x: number = 0;
  output: number = 0;

  if (this.x < 0.5){
    this.output = 1;
  }
  else if ((this.x >= 0.5) && (this.x < 1.0)){
    this.output = 2;
  }
  else {
    this.output = 3;
  }
}

This appears to me to match the tutorials I've read on TypeScript syntax, but apparently something is wrong.

In the Visual Studio Code editor, it says:

  • Duplicate identifier '(Missing)'.ts(2300)
  • Identifier expected.ts(1003)
  • Parameter '(Missing)' implicitly has an 'any' type, but a better type may be inferred from usage.ts(7044)

And, when I go to run the code, the debug console says:

[WDS] Errors while compiling. Reload prevented.
(webpack)-dev-server/client:162
app.component.ts(10,11): error TS1005: ',' expected.
app.component.ts(10,22): error TS1005: ',' expected.
app.component.ts(10,24): error TS1003: Identifier expected.
app.component.ts(13,3): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.

2 Answers 2

2

Your code is not in a function.

Not sure what you are trying to achieve.

You can as example put your code in the constructor function:

export class AppComponent {
  x = 0; // note that the type is inferred therefore the type declaration is not necessary
  output = 0;

  constructor() {
    if (this.x < 0.5){
      this.output = 1;
    }
    else if ((this.x >= 0.5) && (this.x < 1.0)){
      this.output = 2;
    }
    else {
      this.output = 3;
    }
  }
}
1
  • Thank you! That makes sense, and it solved my problem. I didn't realize I could declare variables, but not execute code, inside of a class but outside of a function. Commented Aug 4, 2020 at 7:32
1

You can't just throw some statements in the middle of a class and expect it to work. You have to create class methods or add the statements to the class' constructor or to angular lifecycle hooks.

I.E.

constructor() {
  if (this.x < 0.5){
    this.output = 1;
  }
  else if ((this.x >= 0.5) && (this.x < 1.0)){
    this.output = 2;
  }
  else {
    this.output = 3;
  }
} 

or myFunct() { ... code } and then you call this.myFunct() from somewhere.

Not the answer you're looking for? Browse other questions tagged or ask your own question.