Cloneable
@ts-rust/std / Types / Cloneable
Type Alias: Cloneable<T>
type Cloneable<T> = T extends Primitive ? T : T extends Clone<T> ? T : never;
Defined in: packages/std/src/types.ts:56
Defines a type T
that is cloneable, capable of being duplicated either
implicitly as a Primitive or explicitly via a Clone implementation.
The Cloneable type encompasses all values that can be cloned into a new, independent instance. It is a union of:
- Primitive type: JavaScript primitives (e.g.,
number
,string
,boolean
) that are inherently copied by value through assignment. - Clone types: Types that provide an explicit
clone()
method to create a duplicate instance ofT
.
Inspired by Rust's distinction between Copy
and Clone
, this type captures:
- Implicit cloning: For Primitive types, where assignment
(e.g.,
let y = x
) creates a new copy due to their value semantics. - Explicit cloning: For Clone types, where a
clone()
method must be invoked to produce a new instance.
This type is broader than Clone alone, as it includes both implicitly
copyable primitives and explicitly cloneable types. For
non-primitive types, the clone()
method should return a distinct instance,
though the depth of the copy (shallow or deep) depends on the implementation.
Type Parameters
Type Parameter |
---|
|
Example
// Primitive satisfies Cloneable<number>
const num: Cloneable<number> = 42;
const numCopy = num; // Implicitly copied by value
console.log(numCopy === num); // true (same value)
// Class satisfies Cloneable<MyType> via Clone<MyType>
class MyType implements Clone<MyType> {
constructor(public value: number) {}
clone(): MyType {
return new MyType(this.value);
}
}
const original = new MyType(42);
const duplicate = original.clone();
console.log(duplicate.value === original.value); // true (same value)
console.log(duplicate !== original); // true (different reference)