How do you type a class decorator in typescript?

What would be the correct way to create a class decorator that only accepts certain classes?

I tried the following:

class Component {
  age: number;
}

function registerComponent(name: string) {
  return <T extends Component>(constructor: T): T => {
    return constructor as T;
  }
}

@registerComponent("demo")
class C1 extends Component {

}

      

Result:

Argument of type 'typeof C1' is not assignable to parameter of type 'Component'.
  Property 'age' is missing in type 'typeof C1'.

      

Try it in TypeScript Repl

+3


source to share


1 answer


What is passed to the decorator is a type, not an instance of the type. Expression constructor: T

means constructor

must be an instance of the type T

, so instead you must tell it that the parameter and the result are constructors for the type T

:

class Component {
  age: number;
}

function registerComponent(name: string) {
  return <T extends Component>(constructor: new () => T): new () => T => {
    return constructor;
  }
}

@registerComponent("demo")
class C1 extends Component {

}

      



and you get an extra +1 to enable typescript repl if I could. It was very easy for me to check my answer.

Note that you can also specify constructor parameters.

+4


source







All Articles