TypeScript: pass generic type as parameter in generic class

后端 未结 3 556
一个人的身影
一个人的身影 2021-01-05 17:23

TypeScript: I have a method in the DataProvider class with a method getTableData:

public static getTableData(ty         


        
相关标签:
3条回答
  • 2021-01-05 17:37

    Generics are just metadata. They cannot be used as parameters when calling a function. Maybe you need something like this:

    export class ViewModelBase<T extends DataObject> {
      constructor(private Cl: {new(): T}) {
      }
      public getData(): Array<T> {
        return DataProvider.getTableData<T>(this.Cl);
      }
    }
    
    0 讨论(0)
  • 2021-01-05 17:40

    maybe this would help:

    export abstract class BaseEntity {
      public static from<T extends BaseEntity>(c: new() => T, data: any): T {
        return Object.assign(new c(), data)
      }
      public static first<T extends BaseEntity>(c: new() => T, data) {
        if (data.rows.length > 0) {
          let item = data.rows.item(0);
          return BaseEntity.from(c, item);
        }
        return null;
      }
    
    }
    

    This class can be extended by others so you could call methods on the base class or on its subclasses.

    For instance:

    return Product.first(Product, data);
    

    Or:

    return BaseEntity.first(Product, data);
    

    See how from() method is called from inside first()

    0 讨论(0)
  • 2021-01-05 17:43

    How about defining a base type and extending it? Then your function could expect the base type, and you could call it with the extended type. e.g:

    export interface BaseData {
      key: object
    }
    

    Then:

    import { BaseData } from 'baseDataFile'
    
    export interface DerivedData extends BaseData {
      key: someObjectType
    }
    

    Now:

    import { BaseData } from 'baseDataFile'
    
    export const someFunc = (props: BaseData) => {
        // do some stuff
        return something 
    }
    

    Finally:

    import { DerivedData } from 'derivedDataFile'
    
    const myData: DerivedData = something as DerivedData
    const myNewData = someFunc(myData)
    
    0 讨论(0)
提交回复
热议问题