I am trying to configure Knexfile in TypeScript. I created knexfile.ts with knex init -x ts:
const defaults = { client: 'postgresql', connection: { host: DB_HOST, user: DB_USER, password: DB_PASSWORD, database: DB_DATABASE }, pool: { min: 2, max: 10 }, migrations: { tableName: 'knex_migrations' } }; const knexConfig = { local: { client: 'sqlite3', connection: { filename: './dev.sqlite3' } }, development: { ...defaults, debug: true, useNullAsDefault: true }, production: { ...defaults } }; export default knexConfig; And then I create knex.ts file to make connection:
import Knex, { Config } from 'knex'; import knexConfig from '../utils/knexfile'; import { NODE_ENV } from '../utils/config'; // Set environment from `.env` const knex = Knex(knexConfig[NODE_ENV]); export default knex; But I got an error at (knexConfig[NODE_ENV]), saying that:
(alias) const NODE_ENV: string import NODE_ENV Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ local: { client: string; connection: { filename: string; }; }; development: { debug: boolean; useNullAsDefault: boolean; client: string; connection: { host: string; user: string; password: string; database: string; }; pool: { ...; }; migrations: { ...; }; }; production: { ...; }; }'. No index signature with a parameter of type 'string' was found on type '{ local: { client: string; connection: { filename: string; }; }; development: { debug: boolean; useNullAsDefault: boolean; client: string; connection: { host: string; user: string; password: string; database: string; }; pool: { ...; }; migrations: { ...; }; }; production: { ...; }; }'.ts(7053) ========================================================
What am I doing wrong? Please help.
22 Answers
I believe you can either supress these errors by setting:
"suppressImplicitAnyIndexErrors": true, in your tsconfig.json
or you can create an index signature for the knexConfig object in some way:
interface KnexConfig { [key: string]: object; }; const knexConfig: KnexConfig = { local: { client: 'sqlite3', connection: { filename: './dev.sqlite3' } }, development: { ...defaults, debug: true, useNullAsDefault: true }, production: { ...defaults } }; For more possibilities see the possible duplicate of this question: How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?
1For the future, at version ^1.0.4, knex export all types in Knex interface, so
import { Knex } from "knex"; and get the config autocomplete
module.exports = { client: "mysql", connection: { filename: path.resolve(__dirname, "src", "database", "connection.ts"), }, migrations: { directory: path.resolve(__dirname, "src", "database", "migrations"), }, } as Knex.Config;