mattpocock / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's

Home Page:https://www.totaltypescript.com/ts-reset

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

zanminkian opened this issue · comments

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

Example

const obj = {
  a: 123
}

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

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 🙁