Search code examples
angularngxstypescript-decorator

NGXS action type


I'm wondering why there's no decorator for defining the action type string, instead of declaring a static constant/variable each time you declare an action name.

I though about something like this:

function ActionType(type: string) {
  return (ctor: Function) => {
    ctor.type = type;
  }
}

@ActionType('Hello World !')
class MyAction {

}

I'm not sure if adding type to the constructor is equivalent to a static member, but I do know that after using the decorator, console.log(MyAction.type) would print Hello World ! as it would if we declared a static member.

Would that work ?


Solution

  • I think you're lookng fo r something like this:

    function decorate(typ: string) {
      return function <T extends {new (...args) }>(cls: T): T & { type: string } {
        return class extends cls { 
          static type: string = typ;
        }
      }
    }
    @decorate("")
    class Foo {
        static bar() {
            return 42
        }
    }
    
    Foo.type // ''
    

    Weird parts:

    (arg: T) means that arg is instance of T class. arg: { new (...args): T} means that arg is class T (not a instance)

    & operator is merge types from two interfaces e.g. { key1: string } & { key2: number } is equal { key1: string, key2: number }

    return class extends cls means we return anonymous class that extends cls (in that case Foo). We're adding static type: string to it because we forced that by T & { type: string } part

    Playground