我正在从 angular 转向 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 文件中?如果是这样,打字稿将如何推断导入的类型。
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句