client-ts icon indicating copy to clipboard operation
client-ts copied to clipboard

Generated code errors when compiling with TS declarations

Open mattapperson opened this issue 2 years ago • 2 comments

Describe the bug

When using xata codegen in a project that is compiled as a library with "declaration": true, this results in an error TS18046

  • init a ts package project with "declaration": true
  • setup Xata as a dependency and run xata codegen to create the client code
  • compile the package using tsc

Expected behavior

the project to compile with emitted declaration files

Software version @xata.io/[email protected]

Fix In: /packages/codegen/src/codegen.ts

Change:

  const databaseClient = sourceFile.getVariableDeclaration('DatabaseClient');
  const databaseClientContent = `buildClient()`;

  if (!databaseClient) {
    sourceFile.addVariableStatement({
      declarationKind: VariableDeclarationKind.Const,
      declarations: [{ name: 'DatabaseClient', initializer: databaseClientContent }],
      leadingTrivia:
        language === 'javascript' ? `\n/** @type { import('../../client/src').ClientConstructor<{}> } */\n` : undefined,
      trailingTrivia: '\n'
    });
  } else {
    databaseClient.setInitializer(databaseClientContent);
  }

to

  const databaseClient = sourceFile.getVariableDeclaration('ClientConstructor');
  const databaseClientContent = `buildClient()`;

  if (!databaseClient) {
    sourceFile.addVariableStatement({
      declarationKind: VariableDeclarationKind.Const,
      declarations: [{ name: 'ClientConstructor', initializer: databaseClientContent }],
      leadingTrivia:
        language === 'javascript' ? `\n/** @type { import('../../client/src').ClientConstructor<{}> } */\n` : undefined,
      trailingTrivia: '\n'
    });
  } else {
    databaseClient.setInitializer(databaseClientContent);
  }

mattapperson avatar Feb 13 '23 22:02 mattapperson

Hey @mattapperson, thanks for opening the issue!

Can you provide the error that you receive by tsc? I don't understand how changing the variable name to the type would make any difference (unless the error is elsewhere). I will arrange some time to replicate it myself, but with the error message I could probably see the underlying problem.

SferaDev avatar Feb 14 '23 08:02 SferaDev

TS2307. The issue is TSC won't add an import, and it's not smart enough to infer types that do not match naming.

mattapperson avatar Feb 14 '23 12:02 mattapperson