env-schema icon indicating copy to clipboard operation
env-schema copied to clipboard

Typing `separator` with an array instead of just string

Open jm42 opened this issue 2 years ago • 0 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

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[]
}

jm42 avatar Jul 11 '23 11:07 jm42