简体   繁体   中英

How to import/export a type definition with a typescript file

I am moving over to vue from angular and trying to implement a 'service' as a simple typescript class. I was wondering how I would go about this, currently I have:

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)
    }
}

as my class. Then I try and import it into my vue component:

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

but I get the error:

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

so then I tried throwing a default interface before the class and still get the same error:

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)
    }
}

What is the correct way to do this? Does the type have to be in an external .d.ts file? If so how will typescript infer the type on import.

textSearch is an instance method of the Google class. You are only importing the Google class and not an instance. You need to create an instance to access textSearch method:

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

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

Or if you wanted to export an instance of Google class you can do so:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM