[英]How to import/export a type definition with a typescript file
我正在從角度出發進行探討,並試圖將“服務”實現為簡單的打字稿類。 我想知道如何解決這個問題,目前我有:
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文件中? 如果是這樣,打字稿將如何推斷導入的類型。
textSearch
是Google
類的實例方法。 您僅導入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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.