envsafe
envsafe copied to clipboard
Map choices array to union types
This is a great QoL addition that I've been using a lot from ts-dotenv, but the implementation details of this library is so different that another approach is better. In ts-dotenv you specify an array that are cast as const as so:
LOG_LEVEL: {
type: [
'fatal' as const,
'error' as const,
'warn' as const,
'info' as const,
'debug' as const,
'trace' as const
],
default: 'info'
},
which gives you the type
'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'
It would be amazing if we could conditionally do this for choices. Here is an example of how it can be done:
function stringLiteralArray<T extends string>(a: T[]) {
return a;
}
const fruits = stringLiteralArray(["Apple", "Orange", "Pear"]);
type Fruits = typeof fruits[number]
Agreed! Would be nice.
I've actually started using zod for env vars instead of my own package as I have it installed anyway. See here for an example:
- https://github.com/trpc/examples-next-prisma-starter/blob/main/src/server/env.js
- Validated as part of the build: https://github.com/trpc/examples-next-prisma-starter/blob/main/next.config.js#L3
- Specific env vars can be exposed to client: https://github.com/trpc/examples-next-prisma-starter/blob/main/next.config.js#L27 and inferred safely https://github.com/trpc/examples-next-prisma-starter/blob/main/src/utils/publicRuntimeConfig.ts