我刚刚使用TypeScript下载了Ionic 2示例项目,并希望创建以下类:
export class Accomodation {
private longitude:number;
private latitude:number;
private name:string;
constructor(public long, public lat, public name) {
this.longitude = long;
this. latitude = lat;
this.name = name;
}
get longitude():number {
return this.longitude;
}
set longitude(value:number) {
this.longitude = value;
}
get latitude():number {
return this.latitude;
}
set latitude(value:number) {
this.latitude = value;
}
get name():string {
return this.name;
}
set name(value:string) {
this.name = value;
}
}
我这样使用它:
import {Injectable} from 'angular2/core';
import {Accomodation} from "../model/Accomodation";
@Injectable()
export class LocationService{
static getLocations(){
var location1 = new Accomodation(10, 10, "A beautiful place");
var location2 = new Accomodation(20, 20, "A wonderful place");
var allLocations = [location1, location2];
return Promise.resolve(allLocations);
}
}
然而,我遇到了错误:
****/Accomodation.ts
Error:(6, 14) TS2300: Duplicate identifier 'longitude'.
Error:(7, 14) TS2300: Duplicate identifier 'latitude'.
Error:(8, 14) TS2300: Duplicate identifier 'name'.
Error:(11, 49) TS2300: Duplicate identifier 'name'.
Error:(18, 9) TS2300: Duplicate identifier 'longitude'.
Error:(22, 9) TS2300: Duplicate identifier 'longitude'.
Error:(26, 9) TS2300: Duplicate identifier 'latitude'.
Error:(30, 9) TS2300: Duplicate identifier 'latitude'.
Error:(34, 9) TS2300: Duplicate identifier 'name'.
Error:(38, 9) TS2300: Duplicate identifier 'name'.
我不知道发生了什么事。谷歌搜索没有帮助 任何想法我能做什么?
答案 0 :(得分:4)
声明像constructor(public long, public lat, public name)
这样的构造函数,就是这样的语法糖:
public longitude:number;
public latitude:number;
public name:string;
constructor(longitude, latitude, name) {
this.longitude = longitude;
this.latitude = latitude;
this.name = name;
}
但是你已经声明了这些属性(作为私有),因此Typescript编译器会为每个属性看到两个不同的声明。
您可以执行以下操作之一:
private longitude:number;
private latitude:number;
private name:string;
constructor(long, lat, name) {
this.longitude = long;
this.latitude = lat;
this.name = name;
}
或(未先声明任何内容)
constructor(private longitude:number, private latitude:number, private name:string) {}
此外,您的getter / setter与私有属性具有相同的名称可能是一个问题。通常的做法是使用_
前缀命名私有属性。