0

I'm a TypeScript newb trying to write a Node.js (Node.ts?) backend, and trying to go about the basics of setting up my server. I'm using ts-node version 8.6.2 and typescript version 3.7.5, and defining validation for some domain objects in the following way (in the ajv style):

// domain_obj_1.ts:
const commonSchema = {
  type: 'object',
  properties: {
    foo: { type: 'string' },
  },
};

export class DomainObject1 {
...
// domain_obj_2.ts:
const commonSchema = {
  type: 'object',
  properties: {
    bar: { type: 'string' },
  },
};

export class DomainObject2 {
...

However, ts-node-dev is spitting out the following error:

error TS2403: Subsequent variable declarations must have the same type. 
Variable 'commonSchema' must be of type '{ type: string; properties: { foo: { type: string; }; }; }',
but here has type '{ type: string; properties: { bar: { type: string; }; }; }'.

I can only assume Typescript is detecting a collision of these separate declarations of commonSchema, but they're not being exported so I'm not sure how that's happening.

There's a lot I don't yet understand about TS and its use in Node, but this is surprising behavior and I'm wondering if there's something obvious I'm missing.

Chris
  • 909
  • 8
  • 18

1 Answers1

0

Figured out a way to get ts-node-dev to stop yelling at me, and it indicates there were at least a couple things wrong with my set-up. Hopefully this answer might provide enough breadcrumbs for someone else struggling with standing their own builds up:

  1. I had require('ts-node/register') at the top of each of my knex migration files so I can write the code in modern ES syntax. Turns out this was probably causing a double-compilation problem which seems like has some unpredictable downstream effects.

  2. It also turns out ts-node, which backs ts-node-dev, needs to explicitly be told where tsconfig.json file lives, either by setting the TS_NODE_PROJECT environment variable or passing the --project (-P) flag.

Addressing #1 seems to be sufficient to resolve the errors I was seeing, but for the sake of correctness I'm also addressing the missing config file so eventual compilation in prod is predictable.

Chris
  • 909
  • 8
  • 18