#TS2415 with TypeScript 5, class decorators?

6 messages · Page 1 of 1 (latest)

rain moss
#
function logged<
  T extends object,
  V extends unknown[]
>(
  value: { new(...args: V): T },
  context: DecoratorContext
)
{
  const { kind, name } = context;
  if (kind === "class") {
    return class extends value {
      constructor(...args: V) {
        console.log(`constructing an instance of ${name as string} with arguments ${args.join(", ")}`);
        super(...args);
      }
    }
  }
  return;
}

@logged<C, [n: number]>
class C {
  constructor(n: number) {
    void(n);
  }
}

new C(1);

On the return class part, I get:

Class '(Anonymous class)' incorrectly extends base class 'T'.
  '(Anonymous class)' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'object'.

It's not immediately obvious how I fix this. Example borrowed from https://github.com/tc39/proposal-decorators

GitHub

Decorators for ES6 classes. Contribute to tc39/proposal-decorators development by creating an account on GitHub.

polar thorn
#

i don't really use decorators or dynamically extend classes like this, so i'm no expert, but i think you have to write it a particular way to get "mixin" semantics:

mild karmaBOT
#
mkantor#7432

Preview:ts function logged<C extends new (...args: any[]) => object>( value: C, context: DecoratorContext ) { const { kind, name } = context; if (kind === "class") { return class extends value { constructor(...args: any[]) { console.log(`constructing an instance of ${name as string} with arguments ${args.join(", ")}`); super(...args); } } } return; } ...

polar thorn
rain moss
#

Decorators are brand-new in TypeScript 5, which will be released in a couple weeks... (yes, I know about experimental-decorators. This isn't that.)

old bobcat
#

i don't think it's possible to fix it