Comprehensive guide to all data manipulation methods in Conf, including getting, setting, deleting configuration values with full type safety and dot notation support.
Methods for retrieving configuration values with support for default values and type-safe access.
/**
* Get a configuration value by key
* @param key - The key to retrieve
* @returns The value or undefined if not found
*/
get<Key extends keyof T>(key: Key): T[Key];
/**
* Get a configuration value with a default fallback
* @param key - The key to retrieve
* @param defaultValue - Value to return if key doesn't exist
* @returns The value or defaultValue
*/
get<Key extends keyof T>(key: Key, defaultValue: Required<T>[Key]): Required<T>[Key];
/**
* Get nested property via dot notation
* @param key - Dot notation key (e.g., "user.preferences.theme")
* @returns The nested value or undefined
*/
get<Key extends DotNotationKeyOf<T>>(key: Key): DotNotationValueOf<T, Key>;
/**
* Get nested property via dot notation with default
* @param key - Dot notation key
* @param defaultValue - Value to return if key doesn't exist
* @returns The nested value or defaultValue
*/
get<Key extends DotNotationKeyOf<T>>(key: Key, defaultValue: NonNullable<DotNotationValueOf<T, Key>>): NonNullable<DotNotationValueOf<T, Key>>;
/**
* Generic get method for arbitrary keys (loses type safety)
* Used for keys not known at compile time or dynamic property access
* @param key - Any string key not in the typed schema
* @param defaultValue - Optional default value
* @returns The value, defaultValue, or undefined
*/
get<Key extends string, Value = unknown>(key: Exclude<Key, DotNotationKeyOf<T>>, defaultValue?: Value): Value;Usage Examples:
interface AppConfig {
username: string;
preferences: {
theme: "light" | "dark";
notifications: boolean;
};
lastLogin?: Date;
}
const config = new Conf<AppConfig>({
projectName: "my-app",
defaults: {
username: "guest",
preferences: {
theme: "light",
notifications: true
}
}
});
// Basic property access
const username = config.get("username"); // Type: string
const lastLogin = config.get("lastLogin"); // Type: Date | undefined
// With default values
const safeUsername = config.get("username", "anonymous"); // Type: string
const safeLastLogin = config.get("lastLogin", new Date()); // Type: Date
// Dot notation for nested properties
const theme = config.get("preferences.theme"); // Type: "light" | "dark" | undefined
const safeTheme = config.get("preferences.theme", "light"); // Type: "light" | "dark"
// Dynamic keys (loses type safety)
const dynamicValue = config.get("some.dynamic.key", "default");
// Example of generic get method usage
const userProvidedKey = getUserInput(); // e.g., "user.settings.custom"
const customValue = config.get(userProvidedKey, null); // Type: unknown | nullMethods for storing configuration values with validation and type checking.
/**
* Set a configuration value by key
* @param key - The key to set
* @param value - The value to store (must be JSON serializable)
*/
set<Key extends keyof T>(key: Key, value?: T[Key]): void;
/**
* Set nested property via dot notation
* @param key - Dot notation key (e.g., "user.preferences.theme")
* @param value - The value to store
*/
set<Key extends DotNotationKeyOf<T>>(key: Key, value?: DotNotationValueOf<T, Key>): void;
/**
* Set value with generic key
* @param key - Any string key
* @param value - The value to store
*/
set(key: string, value: unknown): void;
/**
* Set multiple values at once
* @param object - Object containing key-value pairs to set
*/
set(object: PartialObjectDeep<T>): void;Usage Examples:
// Set individual properties
config.set("username", "john_doe");
config.set("preferences", { theme: "dark", notifications: false });
// Set nested properties with dot notation
config.set("preferences.theme", "dark");
config.set("preferences.notifications", false);
// Set multiple properties at once
config.set({
username: "jane_doe",
preferences: {
theme: "light"
},
lastLogin: new Date()
});
// Nested object updates (preserves other properties)
config.set({
preferences: {
theme: "dark" // Only updates theme, preserves notifications
}
});
// Validation errors for invalid data (when schema is defined)
try {
config.set("preferences.theme", "invalid"); // Error if schema restricts values
} catch (error) {
console.error("Validation failed:", error.message);
}Methods for determining if configuration keys exist.
/**
* Check if a key exists in the configuration
* @param key - The key to check
* @returns true if key exists, false otherwise
*/
has<Key extends keyof T>(key: Key): boolean;
/**
* Check if nested property exists via dot notation
* @param key - Dot notation key to check
* @returns true if nested property exists, false otherwise
*/
has<Key extends DotNotationKeyOf<T>>(key: Key): boolean;
/**
* Check existence with generic key
* @param key - Any string key to check
* @returns true if key exists, false otherwise
*/
has(key: string): boolean;Usage Examples:
// Check direct properties
if (config.has("username")) {
console.log("Username is configured");
}
// Check nested properties
if (config.has("preferences.theme")) {
console.log("Theme preference is set");
}
// Conditional logic based on existence
const notifications = config.has("preferences.notifications")
? config.get("preferences.notifications")
: true; // default value
// Guard against undefined access
if (config.has("lastLogin")) {
const lastLogin = config.get("lastLogin")!; // Safe non-null assertion
console.log("Last login:", lastLogin.toISOString());
}Methods for removing configuration values.
/**
* Delete a configuration value by key
* @param key - The key to delete
*/
delete<Key extends keyof T>(key: Key): void;
/**
* Delete nested property via dot notation
* @param key - Dot notation key to delete
*/
delete<Key extends DotNotationKeyOf<T>>(key: Key): void;
/**
* Delete value with generic key
* @param key - Any string key to delete
*/
delete(key: string): void;Usage Examples:
// Delete direct properties
config.delete("lastLogin");
// Delete nested properties
config.delete("preferences.theme"); // Removes theme but preserves notifications
// Delete entire nested objects
config.delete("preferences"); // Removes all preferences
// Verify deletion
config.set("temp", "value");
config.delete("temp");
console.log(config.has("temp")); // => falseMethods for resetting configuration values to their defaults.
/**
* Reset specific keys to their default values
* @param keys - Keys to reset to defaults (from defaults or schema)
*/
reset<Key extends keyof T>(...keys: Key[]): void;
/**
* Clear all configuration data
* Resets known items to defaults, removes unknown items
*/
clear(): void;Usage Examples:
const config = new Conf<AppConfig>({
projectName: "my-app",
defaults: {
username: "guest",
preferences: {
theme: "light",
notifications: true
}
}
});
// Modify some values
config.set("username", "john");
config.set("preferences.theme", "dark");
config.set("customSetting", "value");
// Reset specific keys to defaults
config.reset("username"); // Back to "guest"
config.reset("preferences"); // Back to { theme: "light", notifications: true }
// Clear everything
config.clear(); // Removes all data, restores defaults where defined
console.log(config.store);
// => { username: "guest", preferences: { theme: "light", notifications: true } }Direct access to the entire configuration object.
/**
* Get or set the entire configuration store
*/
get store(): T;
set store(value: T);Usage Examples:
// Get entire configuration
const allConfig = config.store;
console.log(allConfig);
// => { username: "guest", preferences: { theme: "light", notifications: true } }
// Replace entire configuration
config.store = {
username: "admin",
preferences: {
theme: "dark",
notifications: false
}
};
// Backup and restore
const backup = config.store;
// ... make changes ...
config.store = backup; // Restore from backupProperties for accessing store metadata.
/**
* Get the absolute path to the configuration file
*/
readonly path: string;
/**
* Get the number of top-level keys in the configuration
*/
readonly size: number;Usage Examples:
// Access file information
console.log("Config file location:", config.path);
// => "/Users/username/Library/Preferences/my-app-nodejs/config.json"
console.log("Number of config keys:", config.size);
// => 3 (if there are 3 top-level keys)
// Useful for debugging or logging
console.log(`Config has ${config.size} keys stored at ${config.path}`);Conf instances are iterable, allowing for-of loops and other iteration patterns.
/**
* Iterator for configuration entries
* @returns Iterator yielding [key, value] pairs
*/
[Symbol.iterator](): IterableIterator<[keyof T, T[keyof T]]>;Usage Examples:
// Iterate over all configuration entries
for (const [key, value] of config) {
console.log(`${String(key)}: ${JSON.stringify(value)}`);
}
// Convert to array of entries
const entries = Array.from(config);
console.log(entries);
// => [["username", "guest"], ["preferences", { theme: "light", notifications: true }]]
// Use with destructuring
const configEntries = [...config];
const keys = configEntries.map(([key, _]) => key);
const values = configEntries.map([_, value]) => value);
// Compatible with iteration utilities
const configMap = new Map(config);
const configObject = Object.fromEntries(config);// Utility type for deep partial objects
type PartialObjectDeep<T> = {[K in keyof T]?: PartialObjectDeep<T[K]>};
// Complex utility types for dot notation (implementation details)
type DotNotationKeyOf<T extends Record<string, any>> = // Generates union of valid dot notation keys
type DotNotationValueOf<T extends Record<string, any>, K extends DotNotationKeyOf<T>> = // Gets type of value at dot notation path