objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Error in plugin using TypeScript

Open ozum opened this issue 8 years ago • 3 comments

Hi,

I'm trying to write an Objection plugin using TypeScript, but got following error:

error TS4058: Return type of exported function has or is using name 'Knex' from external module "..." but cannot be named.

Code with Error:

import * as Objection from "objection";

function extendedModel<T extends Objection.ModelClass<Objection.Model>>(Base: T) {
  return class extends Base {
    static isTenantSpecific(): boolean {
      return true;
    }
  };
}

export default extendedModel;

Also adding Knex export doesn't solve the problem:

import * as Knex from "knex";
export { Objection, Knex };

Code without Error: If I add extra declarations, it works without problem:

import * as Objection from "objection";

// ▼▼▼ This declaration solves problem, but it is duplicate work.
declare class ExtendedModel {
  static isTenantSpecific(): boolean;
}

function extendedModel<T extends Objection.ModelClass<Objection.Model>>(Base: T) {
  return <typeof ExtendedModel>class extends Base {  // <<<<<< Type declaration added here
    static isTenantSpecific(): boolean {
      return true;
    }
  };
}

export default extendedModel;
tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "module": "commonJS",
    "outDir": "lib",
    "sourceMap": true,
    "declaration": true,
    "target": "esnext",
    "lib": ["es2015", "es2016", "es2017"],
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "lib", "**/*.spec.ts", "**/*.test.ts", "**/__test-supplements__"]
}

In second example I have to declare types twice (once in class and once in declaration). I will appreciate any suggestions.

Thanks,

ozum avatar Jul 12 '18 09:07 ozum

You should use typeof Model instead of just Model.

// extended-model.ts
import { Model } from "objection";

export function extendedModel(baseModel: typeof Model) {
  return class extends baseModel {
    public static yo() {
      console.log("yay!");

      return this;
    }
  };
}
// my-model.ts
import { Model } from "objection";
import { extendedModel } from "./extended-model.ts"

export default class extends extendedModel(Model) {
}
// index.ts
import MyModel from "./my-model.ts";

MyModel.yo()
  .query()
  .then((r) => console.log(r));

douggr avatar Mar 08 '19 23:03 douggr

I have the same error. typeof Model didn't solve it.

s-appdeveloper avatar May 09 '19 17:05 s-appdeveloper

@s-appdeveloper is correct, simply using typeof Model doesn't resolve the issue.

Just in case anyone else is having this issue, a reference is the visibility-plugin

https://github.com/oscaroox/objection-visibility/blob/master/src/index.ts

hardeep avatar Jan 02 '20 22:01 hardeep