2017-08-11 115 views
1

我正在從角度轉向vue,並嘗試將「服務」實現爲簡單的打字稿類。我想知道如何去做這件事,目前我有:如何用打字稿文件導入/導出類型定義

import axios from 'axios' 
import keys from 'libs/keys/api-keys' 

export default class Google { 

    textSearch(query: string, radius = 5000) { 
     let url = `https://maps.googleapis.com/maps/api/place/textsearch/json?radius=${radius}&query=${query}` + 
      `&key=${keys.googleApiKey}` 

     return axios.get(url) 
    } 
    getPhoto(photoReference: string, maxwidth = 1600) { 
     let url = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=${maxwidth}` + 
      `&photoreference=${photoReference}&key=${keys.googleApiKey}` 

     return axios.get(url) 
    } 
} 

作爲我的課。然後我試圖將其導入到我的VUE組件:

import google from 'src/libs/location/google' 
google.textSearch(params.location) 

,但我得到的錯誤:

Property 'textSearch' does not exist on type 'typeof Google' 

所以後來我試過上課前投擲默認界面,仍然得到了同樣的錯誤:

import axios from 'axios' 
import keys from 'libs/keys/api-keys' 

export default interface Google { 
    textSearch(query: string, radius?: number): void 
} 

export default class Google { 

    textSearch(query: string, radius = 5000) { 
     let url = `https://maps.googleapis.com/maps/api/place/textsearch/json?radius=${radius}&query=${query}` + 
      `&key=${keys.googleApiKey}` 

     return axios.get(url) 
    } 
    getPhoto(photoReference: string, maxwidth = 1600) { 
     let url = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=${maxwidth}` + 
      `&photoreference=${photoReference}&key=${keys.googleApiKey}` 

     return axios.get(url) 
    } 
} 

這樣做的正確方法是什麼?該類型是否必須位於外部.d.ts文件中?如果是的話,打字稿如何推斷導入類型。

回答

2

textSearchGoogle類的實例方法。您只導入Google類,而不是實例。您需要創建一個實例來訪問textSearch方法:

import Google from 'src/libs/location/google' // `Google` is the class here 

let googleInstance = new Google(); 
googleInstance .textSearch(params.location); 

或者,如果你想出口Google類的實例,你可以這樣做:

class Google { 
    textSearch(query: string, radius = 5000) { 
     // ... 
    } 
} 

export default new Google(); 

// And use it like: 
import google from 'src/libs/location/google' // `google` is the instance here 
google.textSearch(params.location); 
+0

當然!我知道我錯過了那裏的一些東西。非常感謝 –