total-typescript / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.72k stars 117 forks source link

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

Open zanminkian opened 5 months ago

zanminkian commented 5 months ago

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

zanminkian commented 5 months ago

Example

const obj = {
  a: 123
}

delete obj.b // type error
Reflect.deleteProperty(obj, 'b') // pass
zanminkian commented 2 weeks ago

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 🙁