sweet-js/sweet-core

Extend native JS / TS objects in a safe way

al6x opened this issue · 1 comments

al6x commented

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.

There’s no way to do it outside literals.