【问题标题】:How to import/export a type definition with a typescript file如何使用打字稿文件导入/导出类型定义
【发布时间】:2018-01-19 10:42:38
【问题描述】:

我正在从 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 文件中?如果是这样,打字稿将如何推断导入时的类型。

【问题讨论】:

    标签: typescript vuejs2 vue-component


    【解决方案1】:

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

    【讨论】:

    • 当然!我知道我在那里遗漏了一些东西。非常感谢
    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 2018-11-06
    • 2020-03-18
    • 1970-01-01
    • 2020-09-08
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多