Skip to content

unable to augment class definition #32185

@trusktr

Description

@trusktr

Search Terms

typescript unable to augment class

Suggestion

I keep running into cases where I want to augment a class that I import from another module.

I know it isn't best practice, but in some cases it is necessary.

Use Cases

F.e. extending a prototype

Examples

At the moment, I'd like to do something like

import {MyClass} from './MyClass';

declare module './MyClass' {
  interface MyClass {
    newMethod(s: string): void;
  }
}

MyClass.prototype.newMethod = (s: string) => { /* ... */};
  // ^---- ERROR, 'MyClass' only refers to a type, but is being used as a value here. ts(2693)

But it won't let me. When I try to do this, tsc complains

'MyClass' only refers to a type, but is being used as a value here. ts(2693)

I always run into this issue when attempting to augment a class.

Oddly, this is the method prescribed over at Module Augmentation, but every time I try it it simply does not work.

Also the other most visible StackOverlow answer by @basarat says it isn't supported with classes.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs More InfoThe issue still hasn't been fully clarified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions