0

将 javascript 代码迁移到 typescript 时面临生成类型的问题。也许我错过了一些微不足道的东西。嵌入了打字稿操场代码。

打字稿游乐场

以下是文件结构。

// endpoint.ts
class Endpoint{
  url: string
  constructor (baseUrl: string,) {
    this.url = `${baseUrl}/${name || this.type}`
  }
  getUrl(route: string) () {
    return `${this.url}/${route}`
  }
}

// api.ts
class Api{
    static baseUrl: string;
    static endpoints: {[K in keyof T]: any};
    constructor() {
      const { baseUrl, endpoints } = (this.constructor as typeof Api)
      const endpointInstances = Object.entries(endpoints).reduce((instances: { [name: string]: any }, [name, value]: [string, any]) => {
          instances[name] = new Endpoint(baseUrl)
        return instances
      }, {})
      Object.assign(this, endpointInstances)
    }
}

// etp/reports.ts
class Reports extends Endpoint {
  static url = 'Reports'
  getReports (designId) {
    return this.getUrl(designId)
  }
}

// etp/index.ts
class Etp extends Api {
  static baseUrl = '/planning/api/v1/'
  static endpoints = {
    reports: Reports
  }
}
export default new Etp()

当为此代码生成类型时,会找到以下内容。

// endpoint.d.ts
export default class Endpoint {
    url: string;
    constructor(baseUrl: string);
    getUrl(route: string): string;
}

// api.d.ts
export default class Api {
    static baseUrl: string;
    static endpoints: any;
    constructor();
}

// etp/reports.d.ts
import Endpoint from '../endpoint';
export default class Reports extends Endpoint {
    static url: string;
    getReports(designId: string): string;
}

// etp/index.d.ts
import Api from '../api';
import Reports from './reports';
declare class Etp extends Api {
    static baseUrl: string;
    static endpoints: {
        reports: typeof Reports;
    };
}
declare const _default: Etp;
export default _default;

但是代码被用作etp.reports.getReports('1234')生成的类型是不可能的。

我想实现以下生成的类型

// etp/index.d.ts
import Api from '../api';
import Reports from './reports';
declare class Etp extends Api {
    static baseUrl: string;
    static endpoints: {
        reports: typeof Reports;
    };
    reports: typeof Reports;
}
declare const _default: Etp;
export default _default;

我尝试过将索引签名与 Generic 一起使用,这是不允许的。试图创建 mixins,但在概念上迷失了方向。

4

0 回答 0