xataio / client-ts

Xata.io SDK for TypeScript and JavaScript
https://xata.io/docs/sdk/typescript/overview
Apache License 2.0
123 stars 8 forks source link

Generated code errors when compiling with TS declarations #901

Open mattapperson opened 1 year ago

mattapperson commented 1 year ago

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

Expected behavior

the project to compile with emitted declaration files

Software version @xata.io/cli@0.11.8

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);
  }
SferaDev commented 1 year ago

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.

mattapperson commented 1 year ago

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