繁体   English   中英

如何使用打字稿文件导入/导出类型定义

[英]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文件中? 如果是这样,打字稿将如何推断导入的类型。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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