sweet-js / sweet-core

Sweeten your JavaScript.
https://www.sweetjs.org
BSD 2-Clause "Simplified" License
4.58k stars 208 forks source link

Extend native JS / TS objects in a safe way #754

Closed al6x closed 5 years ago

al6x commented 5 years ago

I wonder if it would be possible to use sweetjs to extend native objects like Array, Object, String etc. in a safe way, without attaching anything to their prototype?

It seems like sweet.js should be able to transform this JS code

{ a: 1 }.isEmpty()

Into

Extensions.isEmpty({ a: 1 })

And the implementation could be

Extensions.isEmpty = (o) => {
  if ('isEmpty' in o) return o.isEmpty()
  for (const k in o) if (o.hasOwnProperty(k)) return false
  return true
}

But I'm not sure what code should I write in Sweet.JS to make that work?

P.S.

And with TypeScript it should work even better. We can trick TypeScript into thinking that our objects are extended by giving it false declaration below, and then after TypeScript compilation apply Sweet.JS compilation.

declare global {
  interface Object {
    isEmpty(): boolean
  }
}

So we get all the correct typings for extensions, and our native objects would stay perfectly clean.

vendethiel commented 5 years ago

There’s no way to do it outside literals.