Logos DX
    Preparing search index...

    Function castValuesToTypes

    • Coerces string values in an object to their appropriate types. Converts "true"/"false" to booleans, numeric strings to numbers, etc. Recursively processes nested objects.

      IMPORTANT: This function mutates the input object in place.

      INTENTION: This is a best-effort coercion based on common string patterns. It does not handle all edge cases and should be used with caution. The goal is to convert typical string representations of booleans and numbers to their actual types, while leaving other strings unchanged.

      USE CASE: Parsing environment variables or other flatmap configuration objects.

      Parameters

      • obj: object

        The object whose values should be coerced (mutated in place).

      • opts: {
            parseUnits?: boolean;
            skipConversion?: (key: string, value: unknown) => boolean;
        } = {}

        Optional configuration options

        • OptionalparseUnits?: boolean

          Optional flag to parse unit values like '5m', '10mb'. Default is false.

        • OptionalskipConversion?: (key: string, value: unknown) => boolean

          Optional function to skip conversion for specific keys. Default is to convert all keys.

      Returns void

      const config = {
      debug: 'true',
      port: '3000',
      nested: {
      enabled: 'false',
      retries: '5'
      }
      };

      castValuesToTypes(config);

      console.log(config);
      // {
      // debug: true,
      // port: 3000,
      // nested: {
      // enabled: false,
      // retries: 5
      // }
      // }
      const config = {
      timeout: '5m',
      maxUploadSize: '10mb',
      debug: 'true'
      };

      castValuesToTypes(config, { parseUnits: true });

      console.log(config);
      // {
      // timeout: 300000, // 5 minutes in milliseconds
      // maxUploadSize: 10485760, // 10 megabytes in bytes
      // debug: true
      // }
      const config = {
      apiKey: '12345',
      port: '3000'
      };

      // Skip conversion for apiKey (keep it as string)
      castValuesToTypes(config, {
      skipConversion: (key) => key.toLowerCase().includes('key')
      });

      console.log(config);
      // {
      // apiKey: '12345', // Kept as string
      // port: 3000 // Converted to number
      // }