简体   繁体   English

TypeScript:如何将类型声明绑定到import语句

[英]TypeScript: How to bind type declaration to import statement

I'm trying to create a type definition for es6-promisify , a JS package not in the DefinitelyTyped annotations repository. 我正在尝试为es6-promisify创建一个类型定义,这是一个不在DefinitelyTyped批注存储库中的JS包。 Looking at examples in DefinitelyTyped and following TS Deep Dive / Declaration Files , I created a crude annotation that I saved in my project in a vendor.d.ts : 查看DefinitelyTyped中的示例,并查看TS深潜/声明文件 ,创建了一个粗略的注释,并将其保存在我的项目中的vendor.d.ts

declare function promisify(original: (...args: any[]) => any, settings: any): Promise<any>

export = promisify
// export interface promisify { } // or should I do an interface?

Now, considering I import with import promisify = require('es6-promisify') , how do I tell TypeScript that the promisify import is annotated in vendor.d.ts ? 现在,考虑使用import promisify = require('es6-promisify')进行import promisify = require('es6-promisify') ,如何告诉TypeScript promisify导入在vendor.d.ts注释? Currently, tsc keeps returning Could not find a declaration file for module 'es6-promisify'. 'promisify.js' implicitly has an 'any' type. 当前, tsc不断返回Could not find a declaration file for module 'es6-promisify'. 'promisify.js' implicitly has an 'any' type. Could not find a declaration file for module 'es6-promisify'. 'promisify.js' implicitly has an 'any' type. I'm trying to digest TS Docs / Module Resolution but am failing at it so far. 我正在尝试摘要TS文档/模块分辨率,但到目前为止却失败了。

Phrased differently: what's the mechanism used by TypeScript to resolve a declaration file from an import? 措辞不同:TypeScript用于从导入解析声明文件的机制是什么? XY problem warning: maybe I'm doing things wrong and shouldn't do a vendor.d.ts ? XY问题警告:也许我做错vendor.d.ts ,不应该做vendor.d.ts吗? Maybe there's a good reason es6-promisify is not in DT? 也许有很好的理由es6-promisify不在DT中? Feel free to contradict with better ways to reach my goal of making tsc with "noImplicitAny": true happy. 随意与更好的方法相矛盾,以达到我使用"noImplicitAny": true制作tsc的目标"noImplicitAny": true快乐。 Thanks :) 谢谢 :)

The following works for me. 以下对我有用。

es6-promisifiy.d.ts : es6-promisifiy.d.ts

declare module "es6-promisify" {
  export default function promisify(original: (...args: any[]) => any, settings: any): Promise<any>
}

usage: 用法:

import promisify from "es6-promisify";
...
const xyz = promisify(whatever, whatever);

tsconfig.json:

{
    "compilerOptions": {
        ...
        "typeRoots": [
            "./node_modules/@types",
            "./custom_typings"
        ]
    },
    ...
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM