21

I have installed request-promise library and trying to use it in my TypeScript app but without much luck.

If I use it like this:

import {RequestPromise} from'request-promise';

RequestPromise('http://www.google.com')
        .then(function (htmlString) {
            // Process html...
        })
        .catch(function (err) {
            // Crawling failed...
        });

I see this on TS compile output:

error TS2304: Cannot find name 'RequestPromise'.

If I use it this way:

import * as rp from'request-promise';

rp('http://www.google.com')
    .then(function (htmlString) {
        // Process html...
    })
    .catch(function (err) {
        // Crawling failed...
    });

I see an error that says that there is no '.then()' method on object rp.

How do I properly use it with TypeScript?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • 1
    Have you tried `import rp from 'request-promise';` and then using `rp` as you have above? – T.J. Crowder Nov 01 '16 at 08:26
  • Now it compiles, but I see `TypeError: Uncaught error: request_promise_1.default is not a function` now when running the app and calling that code. – Sergei Basharov Nov 01 '16 at 08:32
  • 1
    I tried `import rp = require('request-promise')` and it fixed the error. Thanks! – Sergei Basharov Nov 01 '16 at 08:38
  • I didn't understand why this works until I read [this answer](https://stackoverflow.com/a/35706271/6137628). TL;DR - `import * as` creates a module object, which is not "callable" like a function. – Sherwood Callaway Apr 16 '18 at 22:31

3 Answers3

20

You must import all (*) not just RequestPromise:

import * as request from "request-promise";
request.get(...);

This answer elaborates on the differences between import/from and require.

Dave Clark
  • 2,243
  • 15
  • 32
12

request-promise has a package for typescript

npm i --save-dev @types/request-promise
import { get, put, post } from 'request-promise';

Usage

get(options).then(body => {

    console.log(body)

}).catch(e => reject);
Ericgit
  • 6,089
  • 2
  • 42
  • 53
Ivan Velinov
  • 121
  • 1
  • 3
1

I use request-promise in this way

import * as requestPromise from 'request-promise';

const options = {
    uri: _url,
    proxy: https://example.host.com:0000,
    headers: {
        Authorization: 'Bearer ' + token
    }
};

requestPromise.get(options, (error, response) => {
    if (error) {
        // Do error handling stuff
    } else {
        if (response.statusCode !== 200) {
             // Do error handling stuff
        } else {
             // Do success stuff here
        }
    }
});
Abhilash
  • 457
  • 5
  • 9