I have created a few extensions on some base classes, such as Array
to add some functionality that is commonly used throughout our NestJS app.
Consider the following example:
We have a declaration in a .d file:
// in src/declarations/array.d.ts
declare interface Array<T> {
undupe(key?: (e: T) => any): Array<T>; // method that removes duplicate elements from the array
}
And the corresponding implementation:
// src/implementations/array.implementation.ts
Array.prototype.undupe = function (
this: Array<any>,
key?: (e: any) => any,
): Array<any> {
...
};
In order for this to work, I am also importing src/implementations/array.implementation.ts
in our main.ts
file.
I am now trying to create a new entity that is importing a file that is using .undupe() somewhere in it an I am getting this error while generating a new migration for it using the typeorm CLI:
$ yarn typeorm migration:generate -n 'SomeMigration'
yarn run v1.22.19
warning ../../package.json: No license field
$ node --require ts-node/register ./node_modules/typeorm/cli.js migration:generate -n 'SomeMigration'
Error during migration generation:
<some-file-path-that-is-imported-in-the-new-entity-file> - error TS2339: Property 'undupe' does not exist on type 'number[]'.
292 .undupe();
~~~~~~
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I tried specifically importing src/implementations/array.implementation
in the file that is being imported, but that did not work.
I saw a similar error while using Jest, but I could easily solve that by specifying src/implementations/array.implementation.ts
in the setupFilesAfterEnv
field of our jest config json, like this:
{
...
"setupFilesAfterEnv": ["<rootDir>/src/implementations/array.implementation.ts"]
...
}
Is there something similar for TypeOrm? Or does anyone know another workaround to this?
Similar question I found (with no answers)
After some messing around, I found a way to fix this.
The issue wasn't with TypeORM, but with node (or ts-node) not including the declaration files, and the compiler complaining that the undupe
property does not exist on Array
.
Previously, I had in my package.json
, the following line:
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
I changed this to use ts-node instead:
"typeorm": "ts-node ./node_modules/typeorm/cli.js"
I then had to edit my existing tsconfig.json
file to add these lines:
// tsconfig.json
{
"ts-node": {
"files": true
},
"include": ["src/declarations/*"],
... //rest of my ts-config below
}
Alternatively, I also found that this works as well:
// tsconfig.json
{
"ts-node": {
"files": true
},
"files": ["src/declarations/array.d.ts"],
... //rest of my ts-config below
}
Source for the above can be found here.