Numeric environment variables and TypeScript
parseInt function, and the
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
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
const envLimit = parseInt(process.env.USER_LIMIT || '') const userLimit = Number.isInteger(envLimit) ? envLimit : 20
Node treats all environment variables as strings. ↩
Sign up for my newsletter
A monthly round-up of blog posts, projects, and internet oddments.