Skip to main content
Glama
clone.md1.96 kB
# Clone The `Clone` macro generates a `clone()` method for deep copying objects. This is analogous to Rust's `Clone` trait, providing a way to create independent copies of values. ## Generated Output | Type | Generated Code | Description | |------|----------------|-------------| | Class | `classNameClone(value)` + `static clone(value)` | Standalone function + static wrapper method | | Enum | `enumNameClone(value: EnumName): EnumName` | Standalone function (enums are primitives, returns value as-is) | | Interface | `interfaceNameClone(value: InterfaceName): InterfaceName` | Standalone function creating a new object literal | | Type Alias | `typeNameClone(value: TypeName): TypeName` | Standalone function with spread copy for objects | ## Cloning Strategy The generated clone performs a **shallow copy** of all fields: - **Primitives** (`string`, `number`, `boolean`): Copied by value - **Objects**: Reference is copied (not deep cloned) - **Arrays**: Reference is copied (not deep cloned) For deep cloning of nested objects, those objects should also derive `Clone` and the caller should clone them explicitly. ## Example ```typescript before /** @derive(Clone) */ class Point { x: number; y: number; } ``` ```typescript after class Point { x: number; y: number; static clone(value: Point): Point { return pointClone(value); } } export function pointClone(value: Point): Point { const cloned = Object.create(Object.getPrototypeOf(value)); cloned.x = value.x; cloned.y = value.y; return cloned; } ``` ## Implementation Notes - **Classes**: Uses `Object.create(Object.getPrototypeOf(value))` to preserve the prototype chain, ensuring `instanceof` checks work correctly - **Enums**: Simply returns the value (enums are primitives in TypeScript) - **Interfaces/Type Aliases**: Creates new object literals with spread operator for union/tuple types, or field-by-field copy for object types

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/macroforge-ts/mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server