The Missing Bit

Using promise and fetch with Typescript
February 1, 2017

The current Javascript ecosystem is confusing, and that’s an understatement.

I use Webpack to bundle my Typescript projects to the browser, and until now, I used Q.js and regular XMLThingyRequest.

The time has come to use native Promise and the fetch API. What I wanted is a low friction way to use that in my Typescript projects. By low friction I mean, like I’m using the native API with no shim.

I don’t use babel, as I’ve always been satisfied by Typescript transpiling. But typescript won’t polyfill Promise nor fetch.

The solution is quite simple.

First, add a few packages (javascript dev always starts by ADDING PACKAGES, remember):

yarn add promise @types/promise whatwg-fetch @types/whatwg-fetch

Those two packages and their types counterpart are, it seems, the most used implementation/polyfill.

The small trick, is how you are going to use them.

In your main entry file (like app.tsx, whatever you called it), just add:

import "promise/polyfill"
import "whatwg-fetch"

This will ensure they are added and “polyfilled”. And, as we are using a polyfill, we need to use the correct lib. In your tsconfig.json set your lib like so:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "es2017",
          "dom"
        ]
      }
    }

Using the es2017 lib will get the proper definition for Promise and other language feature.