21
loading...
This website collects cookies to deliver better user experience
I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"title": "MyAppConfig",
"type": "object",
"properties": {
"locale": {
"type": "string",
},
"timezone": {
"type": "string",
},
"logLevel": {
"type": "string",
"enum": ["trace", "debug", "info", "warn", "error", "fatal"]
},
"environment": {
"type": "string",
"enum": ["local", "dev", "staging", "production"]
}
},
"required": ["locale", "timezone", "logLevel", "environment"]
}
interface MyAppConfig {
locale: string,
timezone: string,
logLevel: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
environment: 'local' | 'dev' | 'staging' | 'production',
}
export const config: MyAppConfig = {
locale: 'en-US',
timezone: 'America/New_York',
logLevel: 'info',
environment: 'local',
}
export const baseConfig: Omit<MyAppConfig, 'environment' | 'logLevel'>: {
'locale': 'en-US',
'timezone': 'America/New_York',
}
const localConfig = {
'logLevel': 'debug',
'environment': 'local',
}
export const config: MyAppConfig = { baseConfig, ...localConfig }
interface BaseConfig {
locale: string,
timezone: string
}
interface EnvironmentSpecificConfig {
logLevel: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
environment: 'local' | 'dev' | 'staging' | 'production',
}
type MyAppConfig = BaseConfig & EnvironmentSpecificConfig
export const config: MyAppConfig = {
'locale': 'en-US',
'timezone': 'America/New_York',
'logLevel': 'info',
'environment': 'local',
} as const
// Syntax error: Cannot assign to environment because it is a read-only property.
config.environment = 'production'
tsc
. Maybe he was right all along.