Numeric environment variables and TypeScript

The TypeScript implementation of JavaScript’s standard, built-in objects can be surprisingly unforgiving. Two examples of this are the parseInt function, and the Number.isInteger method.

In TypeScript, parseInt accepts a string; Number.isInteger accepts a number or NaN. Anything else causes a type error. This can cause problems when working with numbers stored in environment variables.

Imagine you have an optional USER_LIMIT environment variable. If USER_LIMIT is not defined, you want to use the fallback value 20.

In JavaScript, you can do something like this.

const userLimit = parseInt(process.env.USER_LIMIT) || 20

TypeScript requires a bit more work. Use the logical OR operator to ensure parseInt does not receive undefined1.

const envLimit = parseInt(process.env.USER_LIMIT || '')
const userLimit = Number.isInteger(envLimit) ? envLimit : 20

Footnotes

  1. Node treats all environment variables as strings. ↩

Sign up for my newsletter

A monthly round-up of blog posts, projects, and internet oddments.