Javascript 每个循环语法的typescript中存在错误
我正在尝试用typescript 2.0.3创建一个类,但我有一些问题,我不知道为什么 这是我的密码Javascript 每个循环语法的typescript中存在错误,javascript,angular,typescript,Javascript,Angular,Typescript,我正在尝试用typescript 2.0.3创建一个类,但我有一些问题,我不知道为什么 这是我的密码 import { Component, OnInit } from '@angular/core'; import {Car} from '../interfaces/car'; class PrimeCar implements Car { constructor(public vin, public year, public brand, public color) {} } @C
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);
}
}
在cloneCar方法中,我在尝试写入时出现以下错误:
for (let prop: string in c) {
...}
Tslint:永远不会重新分配标识符“prop”,请使用const而不是
让
这是我的IDE中的图像捕获:
注意:我在angular project 2.3.0版中使用了这段代码
请帮帮我 变量prop仅用于读取。您没有为它分配任何内容,因此它不会更改。这意味着它应该是const not let。您的IDE是正确的。您正在使用
let
而不是const
声明prop
let
适用于可能发生更改的变量。例如:
let x = 5;
x = 7;
const x = 5;
x = 7; // Throws an error.
我们声明了x
,然后更改了它的值
const
用于不会更改的值。例如:
let x = 5;
x = 7;
const x = 5;
x = 7; // Throws an error.
因此,在您的情况下,由于prop
不会改变,因此必须是一个常量(const
):
检查以获得更深入的理解。首先,它只是一个linting错误,告诉您如果不重新分配变量,最好使用
const
而不是let
第二个问题是,我将使用相同的但只有一行的字符串。这只是一个linting错误,它告诉您使用const而不是let,因为您从未将prop重新赋值为另一个值。仍然存在问题,这个问题是由错误版本的typescript引起的吗?不,这是tslint给您的样式指示。。遵循这条规则是好的。它使代码更易于阅读和维护。是的,我仍在寻找解决方案注意IDE和编译器很少出错。。。除XCode外:D@n00dl3哈哈哈!是 啊您还可以决定哪些内容显示为错误或不显示。因此,这也取决于您如何配置IDE。不管怎样,它们总是对生成更好的代码有很大帮助。IDE的更正帮了我很多忙…:甚至比
Object.assign更干净的方法是使用{…}
。