Search code examples
typescriptknex.js

How to define knex migrations using Typescript


I would like to define a knex migration using TypeScript (v1.5), but do not manage to define the up/down callbacks in a type safe way:

This is what I thought might work (but obviously doesn't):

/// <reference path="../../typings/knex/knex.d.ts" />
/// <reference path="../../typings/bluebird/bluebird.d.ts" />

exports.up = function(k : knex.Knex, Promise : Promise<any>) {
};

exports.down = function(k: knex.Knex, Promise : Promise<any>) {
};

TSC output is error TS2304: Cannot find name 'knex'.

I tried a few variations including adding import knex = require("knex"); but with no luck.

For your reference, the knex.d.ts file declares a module like this:

declare module "knex" {
// ... 
  interface Knex extends QueryInterface { }
  interface Knex {
// ... 
  }
}

Any idea? Or am I trying something impossible here?


Solution

  • The issue is caused by a knex.d.ts file that does not export the Knex interface itself, but instead only exports a function to create the "Knex" instance.

    Solution:

    Change the knex.d.ts file to export Knex itself. For this, replace the export = _ statement at the end of the file with this code block:

    function Knex( config : Config ) : Knex;
    export = Knex;
    

    The working migration looks like this:

    /// <reference path="../../typings/knex/knex.d.ts" />
    /// <reference path="../../typings/bluebird/bluebird.d.ts" />
    import Knex = require("knex");
    
    exports.up = function(knex : Knex, Promise : Promise<any>) {
    };
    
    exports.down = function(knex: Knex, Promise : Promise<any>) {
    };
    

    Works great this way. I will create a pull request to get the updated knex.d.ts into the DefinitlyTyped repository.