Ionic 2 - 重复标识符

Ionic 2 - Duplicate Identifier

我刚用 TypeScript 下载了 Ionic 2 示例项目,想做以下 class:

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'.

我不知道发生了什么。 Google 搜索没有帮助 有什么想法吗?

像您那样声明构造函数 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) {}

此外,您的 getters/setters 与私有属性同名可能是个问题。通常的做法是使用 _ 前缀命名私有属性。