ts-reset icon indicating copy to clipboard operation
ts-reset copied to clipboard

Type safe for `Reflect.deleteProperty(object, string|number|symbol)`

Open zanminkian opened this issue 1 year ago • 2 comments

Reflect.deleteProperty is equivalent to delete operator. Reflect.deleteProperty is modern, but not type safe enough.

zanminkian avatar Feb 05 '24 13:02 zanminkian

Example

const obj = {
  a: 123
}

delete obj.b // type error
Reflect.deleteProperty(obj, 'b') // pass

zanminkian avatar Feb 05 '24 14:02 zanminkian

Adding restriction to function parameters is difficult.

// reflect-delete-property.d.ts
declare namespace Reflect {
  /**
   * Removes a property from an object, equivalent to `delete target[propertyKey]`,
   * except it won't throw if `target[propertyKey]` is non-configurable.
   * @param target Object from which to remove the own property.
   * @param propertyKey The property name.
   */
    function deleteProperty<T extends object>(target: T, propertyKey: keyof T): boolean;
}

// other-file.ts
const a = {b:123};
Reflect.deleteProperty(a, 'c'); // no compiling error 🙁

zanminkian avatar Jun 22 '24 08:06 zanminkian