In this article I will demonstrate how to get started with TypeScript using the BITBOX scaffolding tool for Node.js. To enable TypeScript some minor modifications to the generated code are required, each shown in this article. All of the code used in this tutorial can be found on GitHub.
The goal for this article will be to show how to enable TypeScript types for bitbox. We will utilize the existing BITBOX scaffolding system to create a new project and then show how to make the required updates so that the types can be accessed during development.
Create a new project using bitbox new <project-name> --scaffold node which will leverage the existing BITBOX tooling to setup a new Node.js project directory with a package.json file and other template files.
Initiate TypeScript for the project by typing tsc --init within the project directory. This will generate a file called tsconfig.ts which will contain many configurable options for your TypeScript project. We’ll update the “libs” property to equal [“es2015”] as shown in the capture below. This will allow use of Promises (used heavily by BITBOX sdk) within our TypeScript code by including the ES2015 (aka., EcmaScript 6) library.
Add @types/node as a dependency to the package.json file as shown in the image below. Then run npm install.
The import statements need to be updated for TypeScript to match the following:
Now we can access the BITBOX namespaces, methods, and properties through our IDE as illustrated in the following screen capture:
We can also see the expected inputs and outputs for each available method, as well as a strongly typed return type (i.e., Promise<AddressDetailsResult>). This AddressDetailsResult return type can imported into the project with it’s relevant properties and types readily available during development.
Since the details method can also return an array of address details, we cast with <AddressDetailsResult> so the IDE and compiler knows we are expecting a single AddressDetailsResult object. We can see all of the properties associated with this object when we go to use our new details variable.
Finally we compile the index.ts file using tsc index.ts --lib ‘es2015’ which generates index.js file within the same directory, then run the newly created index.js file to verify the code functions.
This post was written by James Cramer.