I'm trying to make a class with typescript 2.0.3 but I have some problems and I don't know why.
this is my code
import { Component, OnInit } from '@angular/core';
import {Car} from '../interfaces/car';
class PrimeCar implements Car
{
constructor(public vin, public year, public brand, public color) {}
}
@Component({
selector: 'rb-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
displayDialog: boolean;
car: Car = new PrimeCar(null, null, null , null);
selectedCar: Car;
newCar: boolean;
cars: Car[];
constructor() { }
ngOnInit() {
this.cars = [ {vin: '111', year: '5554' , brand: '5646' , color: '6466' },
{vin: '111', year: '5554' , brand: '5646' , color: '6466' },
{vin: '111', year: '5554' , brand: '5646' , color: '6466' },
{vin: '111', year: '5554' , brand: '5646' , color: '6466' }
];
}
showDialogToAdd() {
this.newCar = true;
this.car = new PrimeCar(null, null, null, null);
this.displayDialog = true;
}
save() {
const cars = [...this.cars];
if (this.newCar) {
cars.push(this.car);
} else {
cars[this.findSelectedCarIndex()] = this.car;
}
this.cars = cars;
this.car = null;
this.displayDialog = false;
}
delete() {
const index = this.findSelectedCarIndex();
this.cars = this.cars.filter((val, i) => i !== index);
this.car = null;
this.displayDialog = false;
}
onRowSelect(event) {
this.newCar = false;
this.car = this.cloneCar(event.data);
this.displayDialog = true;
}
cloneCar(c: Car): Car {
const car = new PrimeCar(null, null, null, null);
for (let prop: string in c) {
car[prop] = c[prop];
}
return car;
}
findSelectedCarIndex(): number {
return this.cars.indexOf(this.selectedCar);
}
}
In the cloneCar method, I have this error when trying to write:
for (let prop: string in c) {
...}
Tslint: identifier 'prop' is never reassigned ,use const instead of let
this is an image capture from my IDE: see error here
NB: I'm using this code in angular project version 2.3.0
Some help, please!
To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection.
Your IDE is right. You are declaring prop
with let
and not with const
.
let
is for variables that are subject to change. For example:
let x = 5;
x = 7;
We declared x
and then we changed it's value.
const
is for values that won't change. For example:
const x = 5;
x = 7; // Throws an error.
So, in your case, as prop
doesn't and won't change, has to be a constant (const
):
for (const prop: string in c) {
...}
Check this documentation for a deeper understanding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With