fastify / env-schema

Validate your env variable using Ajv and dotenv
MIT License
212 stars 25 forks source link

Typing `separator` with an array instead of just string #157

Open jm42 opened 1 year ago

jm42 commented 1 year ago

Prerequisites

Fastify version

4.19.2

Plugin version

No response

Node.js version

20.x

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

6.4.1

Description

Hello,

I would like to type ALLOWED_HOSTS as string[] instead of string.

interface ConfigEnv {
  ALLOWED_HOSTS: string
}

export function loadConfig(): ConfigEnv {
  return envSchema({
    schema: {
      type: 'object',
      required: [
        'ALLOWED_HOSTS',
      ],
      properties: {
        ALLOWED_HOSTS: {
          type: 'string',
          separator: ',',
        },
      },
    },
  })
}

Now the actual type of loadConfig().ALLOWED_HOSTS is an array, empty or not. Here the type is incorrect to be string and not string[]. But if I change it I get the error on the line of type: "string":

Type '"string"' is not assignable to type '"array"'.ts(2322)

How can I do? Thanks.

Steps to Reproduce

// a.js
import envSchema = require("env-schema")

interface ConfigEnv {
  ALLOWED_HOSTS: string[]
}

export function loadConfig(): ConfigEnv {
  return envSchema({
    schema: {
      type: 'object',
      required: [
        'ALLOWED_HOSTS',
      ],
      properties: {
        ALLOWED_HOSTS: {
          type: 'string',
          separator: ',',
        },
      },
    },
  })
}

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": [
      "es2020",
      "dom"
    ],
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ],
    "outDir": "dist",
    "resolveJsonModule": true
  },
  "exclude": [
    "node_modules",
    "cdk.out",
    "dist"
  ]
}

Run:

$ ts-node a.ts

Error:

TSError: ⨯ Unable to compile TypeScript:
a.ts(16,11): error TS2322: Type '"string"' is not assignable to type '"array"'.

Expected Behavior

Type ALLOWED_HOSTS as:

interface ConfigEnv {
  ALLOWED_HOSTS: string[]
}