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;
  }
}
3
  • 2
    Can you explain how you'd use such a thing? Is this different from just giving your explicit class some static properties? Commented Dec 21, 2020 at 19:27
  • @jcalz have added a usage example Commented Dec 21, 2020 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. Commented Jan 4, 2021 at 20:53

1 Answer 1

1
+100

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.