Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: clean up explanation #23

Merged
merged 2 commits into from
Oct 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,33 +42,35 @@ import { deepCamelKeys } from 'string-ts'
import { camelCase, mapKeys } from 'lodash-es'
import z from 'zod'

export const EnvSchema = z.object({
const EnvSchema = z.object({
NODE_ENV: z.string(),
})

function getEnvLoose() {
const rawEnv: { NODE_ENV: string } = EnvSchema.parse(process.env)
const rawEnv = EnvSchema.parse(process.env)
const env = mapKeys(rawEnv, (_v, k) => camelCase(k))
// ^? Dictionary<string>

// `Dictionary<string>` is too loose
// TypeScript is okay with this, 'abc' will be of type `string`
// TypeScript is okay with this, 'abc' is expected to be of type `string`
// This will have unexpected behavior at runtime
console.log(env.abc)
}

function getEnvPrecise() {
const rawEnv: { NODE_ENV: string } = EnvSchema.parse(process.env)
const rawEnv = EnvSchema.parse(process.env)
const env = deepCamelKeys(rawEnv)
// ^? { nodeEnv: string }

// Error: Property 'abc' does not exist on type '{ nodeEnv: string; }'
// Our type is more specific, so TypeScript catches this error.
// This mistake will be caught at compile time
console.log(env.abc)
}

function main() {
getEnvLoose() // This will break at runtime
getEnvPrecise() // This will break at development time
getEnvLoose()
getEnvPrecise()
}

main()
Expand Down
Loading