Bri*_*ian 5 javascript commonjs typescript typescript-typings typescript2.0
我正在尝试在 Typescript/React 中使用一个简单的 JS 库,但无法为其创建定义文件。该库是 google-kgsearch ( https://www.npmjs.com/package/google-kgsearch )。它以 CommonJS 风格导出单个函数。我可以成功导入和调用该函数,但无法弄清楚如何将参数类型引用到结果回调。
这是大部分库代码:
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)
}
Run Code Online (Sandbox Code Playgroud)
这是我对其进行建模的尝试。大多数接口对服务返回的结果进行建模:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,我无法从另一个文件引用搜索回调返回的 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();
}
....
}
Run Code Online (Sandbox Code Playgroud)
非常感谢任何有关如何使结果接口对我的调用代码可见而又不会弄乱默认导出的建议。
这里的问题很容易解决。问题是,虽然您已导出KGSearch,但尚未导出KGS包含类型的命名空间。有多种方法可以解决此问题,但我推荐的方法是利用声明合并
您的代码将更改如下
declare module 'google-kgsearch' {
export = KGSearch;
function KGSearch(api: string): KGSearch.KGS;
namespace KGSearch {
// no changes.
}
}
Run Code Online (Sandbox Code Playgroud)
然后从消费代码
import KGSearch = require('google-kgsearch');
const kGraph = KGSearch(API_KEY);
interface State {
value: string;
results: Array<KGSearch.EntitySearchResult>; // works!!
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,每当我们引入环境外部模块声明时,就像我们在全局范围内编写的那样declare module 'google-kgsearch',我们都会污染环境外部模块的全局命名空间(我知道这是一个拗口的问题)。虽然暂时不太可能在您的特定项目中造成冲突,但这意味着如果有人添加了一个@types包,google-kgsearch而您有一个依赖项,而该依赖项又依赖于这个@types包,或者如果google-kgsearch每个人都开始发布自己的类型,我们将遇到错误。
为了解决这个问题,我们可以使用非环境模块来声明我们的自定义声明,但这涉及更多的配置。
我们可以这样做
tsconfig.json
{
"compilerOptions": {
"baseUrl": "." // if not already set
"paths": { // if you already have this just add the entry below
"google-kgsearch": [
"custom-declarations/google-kgsearch"
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
custom-declarations/google-kgsearch.d.ts(名称并不重要,只需要匹配路径)
// do not put anything else in this file
// note that there is no `declare module 'x' wrapper`
export = KGSearch;
declare function KGSearch(api: string): KGSearch.KGS;
declare namespace KGSearch {
// ...
}
Run Code Online (Sandbox Code Playgroud)
通过将其定义为外部模块而不是环境外部模块,这可以使我们免受版本冲突和传递依赖问题的影响。
最后要认真考虑的一件事是向krismuniz/google-kgsearch发送拉取请求,将您的输入(第二个版本)添加到名为index.d.ts的文件中。另外,如果维护者不希望包含它们,请考虑通过向DefinitelyTyped@types/google-kgsearch发送拉取请求来创建包
| 归档时间: |
|
| 查看次数: |
1025 次 |
| 最近记录: |