Typescript: How to let TypeScript work with bluebird promisifyAll or promisify?

Created on 19 May 2016  路  5Comments  路  Source: microsoft/TypeScript

import * as redis from "redis";
import * as Promise from "bluebird";
Promise.promisifyAll(redis);
const redisClient = redis.createClient(); 
redisClient.hexistsAsync("myhash", "field").then(function(v) {

}).catch(function(e) {

});

This code will not work with TypeScript, since it has not enough type information for the promisified redis.

Most helpful comment

You would need to do:

import * as Promise from 'bluebird';
import * as redis from 'redis';
const redisAsync: any = Promise.promisifyAll(redis);

There won't be any intellisense, but it will let you call .xxxAsync().

All 5 comments

Or should I use RxJS instead of bluebird?
I think it is better to use RxJS, since it is typescript based.

You would need to do:

import * as Promise from 'bluebird';
import * as redis from 'redis';
const redisAsync: any = Promise.promisifyAll(redis);

There won't be any intellisense, but it will let you call .xxxAsync().

@JoshGlazebrook Thanks!

Some Javascript magic trick still need dynamic.

How about:

import * as Promise from 'bluebird';
import * as Redis from 'redis';

declare module 'redis' {
  export interface RedisClient extends NodeJS.EventEmitter {
    hdelAsync(...args: any[]): Promise<any>;
    // add other methods here
  }
}

const oldRedisClient = Redis.createClient(...);
const redisClient = Promise.promisifyAll(oldRedisClient) as Redis.RedisClient; // cast

// redisClient.hdelAsync now shows up in intelliSense.

How about

import * as Bluebird from 'bluebird';
import * as AWS from 'aws-sdk';

export interface IPromisifedS3 extends AWS.S3 {
    [x: string]: any
}

const s3 = new AWS.S3();
Bluebird.promisifyAll(s3);

export default s3 as IPromisifedS3;

This enables type checking and auto completion for the normal functions while allowing to use the promosified methods

Was this page helpful?
0 / 5 - 0 ratings