Search code examples
typescriptclass

Add custom properties into an existing class


I'm trying to add a custom property into an existing class but every time I execute the code, I get the following error: Property 'env' does not exist on type 'MyClass'. So I want to do something like this:

class MyClass {
  options = ''
}

const myObject = new MyClass();
myObject.options = 'any';
myObject.env = { token: 'MY_TOKEN' }; // Error: Property 'env' does not exist on type 'MyClass'

Is there a way I can create the env property without getting any errors?


Solution

  • There are certainly better options, among which:

    • modifying the original class;
    • extending the original class;
    • creating a new class, linked to the original class by composition.

    If, for some reasons, you can't or don't want to do any of these, then you can declare the additional properties of your object explicitly:

    const myObject: MyClass & {env?: {token: string}} = new MyClass();