2017-08-11 85 views
1

我正在从角度转向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文件中?如果是的话,打字稿如何推断导入类型。

回答

2

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

当然!我知道我错过了那里的一些东西。非常感谢 –