我想在Typescript/React中使用一個簡單的JS庫,但無法爲它創建一個定義文件。該圖書館是google-kgsearch(https://www.npmjs.com/package/google-kgsearch)。它以CommonJS風格導出單個函數。我可以成功導入並調用該函數,但無法弄清楚如何將參數的類型引用到結果回調函數中。導出用於CommonJS模塊(Typescript)的其他接口
這裏是大多數庫代碼:
function KGSearch (api_key) {
this.search = (opts, callback) => {
....
request({ url: api_url, json: true }, (err, res, data) => {
if (err) callback(err)
callback(null, data.itemListElement)
})
....
return this
}
}
module.exports = (api_key) => {
if (!api_key || typeof api_key !== 'string') {
throw Error(`[kgsearch] missing 'api_key' {string} argument`)
}
return new KGSearch(api_key)
}
這裏是我的嘗試建模。大部分接口模型的服務返回的結果:
declare module 'google-kgsearch' {
function KGSearch(api: string): KGS.KGS;
export = KGSearch;
namespace KGS {
export interface SearchOptions {
query: string,
types?: Array<string>,
languages?: Array<string>,
limit?: number,
maxDescChars?: number
}
export interface EntitySearchResult {
"@type": string,
result: Result,
resultScore: number
}
export interface Result {
"@id": string,
name: string,
"@type": Array<string>,
image: Image,
detailedDescription: DetailedDescription,
url: string
}
export interface Image {
contentUrl: string,
url: string
}
export interface DetailedDescription {
articleBody: string,
url: string,
license: string
}
export interface KGS {
search: (opts: SearchOptions, callback: (err: string, items: Array<EntitySearchResult>) => void) => KGS.KGS;
}
}
}
我的問題是,從另一個文件我無法引用由搜索回調返回的KGS.EntitySearchResult陣列。這是我使用的庫:
import KGSearch = require('google-kgsearch');
const kGraph = KGSearch(API_KEY);
interface State {
value: string;
results: Array<KGS.EntitySearchResult>; // <-- Does not work!!
}
class GKGQuery extends React.Component<Props, object> {
state : State;
handleSubmit(event: React.FormEvent<HTMLFormElement>) {
kGraph.search({ query: this.state.value }, (err, items) => { this.setState({results: items}); });
event.preventDefault();
}
....
}
如何使結果界面看到我的調用代碼不會弄亂默認的導出任何建議,非常非常感謝。
使用'import ... = require('...');贊同CommonJS模塊。這是一個非常好的做法。 –