Declaration Merging For Typed Contexts
Merge interfaces and namespaces with declaration merging so related types stay in one place and extensions type-check without inheritance.
Code
interface UserRecord {
id: string;
email: string;
}
// declaration merging:同名接口在同一作用域继续追加字段
interface UserRecord {
tenantId: string;
roles: readonly string[];
}
namespace Audit {
export const enabled = true;
}
namespace Audit {
export function stamp(record: UserRecord): string {
return record.id + ':' + record.tenantId;
}
}
const user: UserRecord = {
id: 'u-1',
email: '[email protected]',
tenantId: 't-9',
roles: ['admin', 'billing'],
};
console.log('user:', user.id, user.email, user.tenantId);
console.log('roles:', user.roles.join(','));
console.log('audit enabled:', Audit.enabled, '| stamp:', Audit.stamp(user));What the snippet does
The snippet is organized around the function stamp.
Using it
The primary signature is export const enabled =
The demo output is labeled (user:, roles:, audit enabled:), so the printed lines read as a per-operation trace of the run.
enabled is what another module would consume; nothing else here is load-bearing for callers.
Key statements
return record.id + ':' + record.tenantId;
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `stamp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.