打字稿:如何实例化实现一个接口的类,该接口定义了通用函数属性

时间:2019-11-14 22:56:02

标签: typescript typescript-generics

是否可以在Typescript中执行以下操作:

export interface IMyInterface<T> {
  readonly transform: <TF>(response: TF[]) => T[];
}

export class MyClass<T> implements IMyInterface<T> {
  readonly transform?: <TF extends {}>(response: TF[]) => T[];

  constructor(
    transform?: <TF extends {}>(response: TF[]) => T[],
  ) {
    this.transform = transform;
  }
}

type Api = { ID: number; Name: string };
const transformImplementation = (response: Api[]): AnotherType[] => {
  const items: AnotherType[] = response.map(item => {
    return {
      id: item.ID,
      name: item.Name,
    };
  });
  return items;
};

export const requestFactories = {
  getItems: (sourceComponent: string): MyClass<AnotherType> => {
    const url = `${APP_CONF.apiBaseURL}/anotherType`;
    return new MyClass<AnotherType>(
      'GET',
      sourceComponent,
      url,
      transformImplementation,
    );
  },
};

我正在尝试传递在类(MyClass)中定义的泛型函数(transformImplementation)的实现,但似乎无法使其编译?

0 个答案:

没有答案