2017-08-11 18 views
1

私は、角度から見て、単純なtypescriptクラスとして 'サービス'を実装しようとしています。私はこれについてどうやって行くのだろうと思っていましたが、現在私は持っています:タイプコピーファイルを使用して型定義をインポート/エクスポートする方法

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

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

もちろん!私はそこに何かがないことを知っていた。どうもありがとう –

関連する問題