Typescript automatically get interface properties in a class

后端 未结 3 902
一生所求
一生所求 2020-11-29 12:04

Hello TypeScript experts.

I have the following code but I have to repeat the interface properties in the class otherwise I get:

Class incorrec

3条回答
  •  情话喂你
    2020-11-29 12:36

    There is no built-in support for this.

    We can however use a function that returns a class as the base type of our class. This function can lie a little bit and claim it implements the interface. We could also pass in some defaults for the members if necessary.

    interface INavigation {
      Id: number;
      AppId: number;
      NavId: number;
      Name: string;
      ParentId: string;
      PageURL: string;
      Position: string;
      Active: string;
      Desktop: string;
      Tablet: string;
      Phone: string;
      RoleId: string;
      Target: string;
    }
    
    function autoImplement(defaults?: Partial) {
      return class {
        constructor() {
          Object.assign(this, defaults || {});
        }
      } as new () => T
    }
    
    class Navigation extends autoImplement() {
      constructor(navigation: any) {
        super();
        // other init here
      }
    }
    

    If we want to have a base class, things get a bit more complicated since we have to perform a bit of surgery on the base type:

    function autoImplementWithBase any>(base: TBase) {
      return function (defaults?: Partial): Pick & {
        new(...a: (TBase extends new (...o: infer A) => unknown ? A : [])): InstanceType & T
      } {
        return class extends base {
          constructor(...a: any[]) {
            super(...a);
            Object.assign(this, defaults || {});
          }
        } as any
      }
    }
    
    class BaseClass {
      m() { }
      foo: string
      static staticM() { }
      static staticFoo: string
    }
    
    class Navigation extends autoImplementWithBase(BaseClass)() {
      constructor(navigation: any) {
        super();
        // Other init here
      }
    }
    
    Navigation.staticFoo
    Navigation.staticM
    new Navigation(null).m();
    new Navigation(null).foo;
    

提交回复
热议问题