如何将索引集合作为打字稿中的静态属性编写?

时间:2017-08-04 20:09:46

标签: typescript

我希望有一个静态属性列出索引的Store实例,但是无法编译,但有以下错误:

Type '({ '0750078': Store; } | { '0840021': Store; } | { '0840302': Store; })[]' is not assignable to type '{ string: Store; }[]'.
  Type '{ '0750078': Store; } | { '0840021': Store; } | { '0840302': Store; }' is not assignable to type '{ string: Store; }'.
    Type '{ '0750078': Store; }' is not assignable to type '{ string: Store; }'.
      Object literal may only specify known properties, and ''0750078'' does not exist in type '{ string: Store; }'.

有什么想法吗?

export class Geolocation {
    lat:number;
    long: number;
    heading: number;
}

export class Store {
    nim: string;
    name: string;
    address: string;
    geolocation: Geolocation;
    constructor(
        nim: string,
        name: string, 
        address: string, 
        geolocation: Geolocation) {

        this.nim = nim;
        this.name = name; 
        this.address = address; 
        this.geolocation.lat = geolocation.lat;
        this.geolocation.long = geolocation.long;
        this.geolocation.heading = geolocation.heading;     
    }
}

export class Stores {
    store: Store;

    static stores: {string: Store}[] = [
        {'0750078': new Store('0750078', 'Kiosque de Paris',    'Place Colette 75001 Paris',                new Geolocation(48.8632,    2.3363,  90))},
        {'0840021': new Store('0840021', 'Presse tabac',        'Place de l’église 84140 Montfavet',        new Geolocation(43.9361,    4.8717, 180))},
    ];  
}

1 个答案:

答案 0 :(得分:0)

您的静态stores类型不正确。 它应该是Array<{ [x: string]: Store }>

(或{ [x: string]: Store }[]但我更喜欢第一个,因为它更具可读性。)

编辑: 如果您想要一个索引存储,它应该是:

export class Stores {
  store: Store;

  static stores = {
    '0750078': new Store('0750078', 'Kiosque de Paris', 'Place Colette 75001 Paris', new Geolocation(48.8632, 2.3363, 90)),
    '0840021': new Store('0840021', 'Presse tabac', 'Place de l’église 84140 Montfavet', new Geolocation(43.9361, 4.8717, 180))
  }
}

您不必明确键入stores,因为推断类型可以正常工作。