【问题标题】:Nodejs, Typescript, typings: how to use async libraryNodejs、Typescript、打字:如何使用异步库
【发布时间】:2017-02-12 04:48:22
【问题描述】:

我正在尝试在 Typescript 中使用异步库;我已经安装了由 typings 提供的定义文件,但我无法使用 AsyncFunction:

///<reference path='typings/index.d.ts' />
'use strict';

import async = require( 'async' );

let functions : AsyncFunction<any>[] = [];

如果我编译这个提取我得到这个错误:

tsc test.ts --target es2015 --module system --removeComments --forceConsistentCasingInFileNames --noEmitOnError --noFallthroughCasesInSwitch --noImplicitAny --noImplicitReturns --noImplicitUseStrict --declaration --outfile a.js
test.ts(4,17): error TS2304: Cannot find name 'AsyncFunction'.

我使用的异步定义文件是这样的:https://raw.githubusercontent.com/types/npm-async/ff63908a70ec51b775d9a6b8afac9945b12fbe08/2/index.d.ts

我做错了什么?

谢谢!

【问题讨论】:

  • 如果有人遇到同样的问题,我的解决方案是安装全局定义 dt~async

标签: node.js typescript async.js typescript-typings


【解决方案1】:

在项目根文件夹上运行两个命令

npm install async --save

npm i @types/async --save

import * as async from 'async';

async.auto({
    get_data: function(callback:any) {
        console.log('in get_data');
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    make_folder: function(callback:any) {
        console.log('in make_folder');
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    },
    write_file: ['get_data', 'make_folder', function(results:any, callback:any) {
        console.log('in write_file', JSON.stringify(results));
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, 'filename');
    }],
    email_link: ['write_file', function(results:any, callback:any) {
        console.log('in email_link', JSON.stringify(results));
        // once the file is written let's email a link to it...
        // results.write_file contains the filename returned by write_file.
        callback(null, {'file':results.write_file, 'email':'user@example.com'});
    }]
  }, function(err:any, results:any) {
    console.log('err = ', err);
    console.log('results = ', results);
  });

【讨论】:

    【解决方案2】:

    接口AsyncFunction 未从该文件导出。从最后一行的export = async; 可以看出,唯一的导出是async

    修复

    如果您必须使用该注释,请随意将 interface AsyncFunction<T> { (callback: (err?: Error, result?: T) => void): void; } 复制到global.d.ts

    【讨论】:

    • 谢谢,我明白我为什么感到困惑了:异步 v1 定义不使用“模块”,所以所有接口都是直接可用的。
    • @Steve81 您能否详细说明为什么会发生此错误
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2017-05-24
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2017-07-19
    相关资源
    最近更新 更多