How to define static property in TypeScript interface

前端 未结 14 1242
你的背包
你的背包 2020-11-28 05:49

I just want to declare a static property in typescript interface? I have not found anywhere regarding this.

interface myInterface {
  static         


        
14条回答
  •  一生所求
    2020-11-28 06:21

    I found a way to do this (without decorators) for my specific use case.

    The important part that checks for static members is IObjectClass and using cls: IObjectClass in the createObject method:

    //------------------------
    // Library
    //------------------------
    interface IObject {
      id: number;
    }
    interface IObjectClass {
      new(): T;
      table_name: string;
    }
    function createObject(cls: IObjectClass, data:Partial):T {
      let obj:T = (Object).assign({},
        data,
        {
          id: 1,
          table_name: cls.table_name,
        }
      )
      return obj;
    }
    
    //------------------------
    // Implementation
    //------------------------
    export class User implements IObject {
      static table_name: string = 'user';
      id: number;
      name: string;
    }
    
    //------------------------
    // Application
    //------------------------
    let user = createObject(User, {name: 'Jimmy'});
    console.log(user.name);
    

提交回复
热议问题