2017-08-04 58 views
0

我想有一个列出索引存储实例的静态属性,但可惜无法编译,并出现以下错误:如何在索引记录中将索引集合写为静态属性?

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))}, 
    ]; 
} 

回答

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作为推断类型会工作得很好。

+0

我仍然面临一个问题Stores.stores ['0840021']返回undefined?它是怎么来的@unional? –

+0

你有它作为一个数组。 [1]访问第二个元素。你是否想让它成为索引器?这应该是一个对象在这种情况下 – unional

+0

当然,我最初的问题是通过其NIM索引商店(其关键像'0840021')@unional –