Home > Back-end >  How do I validate an environment variable string against an inline union type e.g. <16 | 32 | 64&
How do I validate an environment variable string against an inline union type e.g. <16 | 32 | 64&

Time:06-06

I'm working with the rpi-led-matrix repo to successfully control an LED panel. While it has been super helpful in getting hardware controlled via TypeScript, I'm struggling a bit with its multiple inline union types when attempting to validate my own unknown/string environment variables.

This example works so far when setting the number of LED panel rows option. No validation yet:

config.ts

import * as dotenv from 'dotenv'
import { LedMatrix, MatrixOptions } from 'rpi-led-matrix'

dotenv.config({ path: `${__dirname}/.env` })

export const matrixOptions: MatrixOptions = {
  ...LedMatrix.defaultMatrixOptions(),
  rows: process.env.MATRIX_ROWS
    ? <16 | 32 | 64>Number(process.env.MATRIX_ROWS)
    : LedMatrix.defaultMatrixOptions().rows,
}

To better handle validation and communicate any issues in console, I'm trying to break this out into a utils file:

configUtils.ts

const matrixRowOptions = [16, 32, 64]
type MatrixRowOptions = typeof matrixRowOptions[number]

export const configMatrixRows = (
  configRows?: string | number,
): MatrixRowOptions => {
  const rows = Number(configRows) as MatrixRowOptions
  if (matrixRowOptions.includes(rows)) {
    return rows
  }

  if (rows) {
    console.error(
      `supplied rows value of ${rows} is not a valid option, assigning default of ${
        LedMatrix.defaultMatrixOptions().rows
      }.`,
    )
  }

  return LedMatrix.defaultMatrixOptions().rows
}

new config.ts:

import * as dotenv from 'dotenv'
import { LedMatrix, MatrixOptions } from 'rpi-led-matrix'
import { configMatrixRows } from './configUtils';

dotenv.config({ path: `${__dirname}/.env` })

export const matrixOptions: MatrixOptions = {
  ...LedMatrix.defaultMatrixOptions(),
  rows: configMatrixRows(process.env.MATRIX_ROWS), // <<<            
  • Related