打字稿:如何重载构造函数?

时间:2016-09-01 13:01:06

标签: typescript

我正在尝试重载一个类构造函数,但我似乎没有得到这个概念。我一直在overload signature is not compatible with function implementation

这就是我所看到的:

interface IGeoJson {
  type: string,
  coordinates: [number,number]
}

abstract class GeoJson implements IGeoJson {

  constructor (public type: string, public coordinates: [number,number]) {}

  toJson() : string {
    return JSON.stringify(this);
  }
}

class GeoJsonPoint extends GeoJson {

  /**
   * err: overload signature is not compatible with function implementation
   */
//   constructor ( obj : IGeoJson);
  constructor ( obj : [number, number]) {
      let [longitude, latitude] = obj;
      if (longitude && latitude) {
         super("Point", [longitude, latitude]);
      } 
      else {
        let {type, coordinates} = obj;
        if (type && coordinates) {
            GeoJsonPoint.fromJson(obj);
        }
      }
  }

  static fromJson ( { type, coordinates } : IGeoJson) : GeoJsonPoint {
    if (type != 'Point') throw new Error("Error, expecting type=Point");
    let [longitude, latitude] = coordinates;
    return new GeoJsonPoint([longitude, latitude]);
  }
}





/**
 * runtime
 */

let here = new GeoJsonPoint([10.123,20.456]);
let hereAsJson = here.toJson();
console.log('here:' + hereAsJson);


let obj :IGeoJson = JSON.parse(hereAsJson);
let hereFromJson = GeoJsonPoint.fromJson(obj);
console.log('here From JSON.parse():' + hereFromJson.toJson())

我正在尝试重载构造函数,以便我可以执行以下操作:

let obj = JSON.parse(hereAsJson);
let hereFromOverloadedConstructor = new GeoJsonPoint(obj);
console.log('here From overloaded constructor:' + hereFromOverloadedConstructor.toJson())

1 个答案:

答案 0 :(得分:0)

应该是:

constructor (obj : IGeoJson);
constructor (obj : [number, number]);
constructor(obj: any) {
    let [longitude, latitude] = obj;
    if (longitude && latitude) {
        super("Point", [longitude, latitude]);
    } else {
        let {type, coordinates} = obj;
        if (type && coordinates) {
            GeoJsonPoint.fromJson(obj);
        }
    }
}

code in playground

但您的代码存在问题,因为当您收到super个对象时,请不要致电IGeoJson。 此外,它可以这样做:

constructor(obj: IGeoJson | [number, number]) {
    if (obj instanceof Array) {
        super("Point", obj);
    } else {
        super(obj.type, obj.coordinates);
    }
}

code in playground