1

I need to add properties to Object.constructor on a specific class.

I am Using lib.es5.d.ts

I have tried overriding the global Object like:

type EntityConstructor = Function & {behaviors: string[]}

declare global {
  interface Object {
    constructor: EntityConstructor
  }
}

This throws an error:

Subsequent property declarations must have the same type.  
Property 'constructor' must be of type 'Function', but here has type 'EntityConstructor'.

I don't need this to be an override it could be for a explicit class.

USAGE EXAMPLE: To clarify why and how I want this property...

I am using typescript mixins

I have a method that takes a set of ConstrainedMixin constructors, applies them to a base class to create a new Constructor for the mixed class. Then I want to store the list of applied mixin names on that new constructor as a new property. This looks like:

import compose from 'lodash.flowright';
export type ConstrainedMixin<T = {}> = new (...args: any[]) => T;
class Entity {
  static behaves(...behaviors: Array<ConstrainedMixin>){
    const newEnt = compose.apply(
      null,
      behaviors,
    )(Entity);

    newEnt.behaviors = behaviors.map((behaviorClass) => behaviorClass.name);

    return newEnt;
  }
}
kevzettler
  • 4,783
  • 15
  • 58
  • 103
  • 2
    Can you explain how you'd use such a thing? Is this different from just giving your explicit class some `static` properties? – jcalz Dec 21 '20 at 19:27
  • @jcalz have added a usage example – kevzettler Dec 21 '20 at 21:05
  • Why can't you just add an instance field `behaviors: string[]` to `Entity`? If you are asking the question _"How can change the global object constructor's type?"_ then you are probably doing the _really_ hard way. – Alex Wayne Jan 04 '21 at 20:53

1 Answers1

1

You could do something along the lines of:

type EntityConstructor = Function & {behaviors: string[]}

declare global {
  interface O extends Object {
    constructor: EntityConstructor
  }
}

But you would need to create another class that extends Object. As far as I can tell, there's not really a way to do what you are asking without changing the original Object interface itself / the d.ts file or creating a separate class that extends Object.

Here are some helpful answers on a related question on Overriding Interface Property Types

Zach
  • 880
  • 5
  • 17