Great question! When you use Object.defineProperty() to add non-enumerable properties, TypeScript will indeed not include these properties in the type definition by default.
Here's an example to illustrate:
interface MyObjectType {
name: string;
value: number;
}
const myObject: MyObjectType = {
name: 'example',
value: 42
};
Object.defineProperty(myObject, 'createdAt', {
value: new Date(),
writable: false,
enumerable: false
});
// TypeScript won't complain about the type
// The 'createdAt' property won't show up in type checks or intellisense
If you want to explicitly allow these properties in your TypeScript type, you can extend the interface:
interface MyObjectType {
name: string;
value: number;
createdAt?: Date; // Optional, non-enumerable
}
The Proxy approach would work similarly without modifying the original type. Here's a type-safe version:
function createTrackedObject<T extends object>(obj: T): T & { createdAt: Date, updatedAt: Date } {
return new Proxy(obj, {
set(target, property, value) {
if (property !== 'updatedAt') {
(target as any).updatedAt = new Date();
}
(target as any)[property] = value;
return true;
}
}) as T & { createdAt: Date, updatedAt: Date };
}
// Usage
interface MyObject {
name: string;
value: number;
}
const trackedObject = createTrackedObject<MyObject>({
name: 'example',
value: 42
});
// trackedObject now has createdAt and updatedAt, but doesn't modify the original type
This approach allows you to add timestamps without changing the original object's type definition, which meets your requirement of avoiding type modifications.