Error: ReferenceError: Invalid left-hand side in a

2019-09-20 05:00发布

问题:

I know JavaScript. I'm just learning Typescript and this gives me the error: "Error: ReferenceError: Invalid left-hand side in assignment". What's wrong?

import { Component } from '@angular/core';
import { Fruit } from './fruit';
import { PartComponent } from './part.component';
import { ByKindPipe } from './by-kind.pipe';

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html',
  directives:[PartComponent],
  pipes: [ByKindPipe],
  styles: ['div { color: blue; }']
})
export class AppComponent { 

  // this works
  fruits: Fruit[] = [
            {"name": "apple", "kind": "tree"}, 
            {"name": "orange", "kind":"tree"},
            {"name": "strawberry", "kind": "berry"},
            {"name": "pear", "kind": "tree"}];

  // this works    
  things: string[] = ["a","b"];

  // this doesn't work
  things[1] = "c";
}

Please refer to app/app.component.ts file in this plunk

回答1:

Inside a class body, you can have initialized members. For example, you declared things of type string[]. That's a legal member declaration.

You can't have statements in your class body. The code things[1] = "c"; is a statement. If you want to do something like that, you should put it in the constructor