Skip to content

Printer introduces syntax error into .tsx files #59587

Closed
@maxpatiiuk

Description

@maxpatiiuk

🔎 Search Terms

tsx printer printing syntax error generic type parameter

🕗 Version & Regression Information

  • This is the behavior in every version I tried.
  • Bug occurs here in the TypeScript source code:
    function emitTypeParameters(parentNode: SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration | ClassDeclaration | ClassExpression, typeParameters: NodeArray<TypeParameterDeclaration> | undefined) {
    if (isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
    return emitTypeArguments(parentNode, parentNode.typeArguments);
    }
    emitList(parentNode, typeParameters, ListFormat.TypeParameters);
    }

⏯ Playground Link

https://github.com/maxpatiiuk/typescript-printer-tsx-syntax-error

💻 Code

import ts from 'typescript';

const sourceCode = 'export const id = <T,>(id: T): T => id';
const sourceFile = ts.createSourceFile(
  'index.tsx',
  sourceCode,
  ts.ScriptTarget.Latest,
  undefined,
  ts.ScriptKind.TSX
);

const printer = ts.createPrinter();
const printed = printer.printFile(sourceFile);

console.log('Original:');
console.log(sourceCode); // 'export const id = <T,>(id: T): T => id;'
console.log('Printed:');
console.log(printed); // 'export const id = <T>(id: T): T => id;'

🙁 Actual behavior

The printer removes trailing comma from the generic type parameters list.
That trailing comma is crucial to correctly parse the .tsx files. See how without it TypeScript (and ESBuilt and others) are reporting a syntax error: https://www.typescriptlang.org/play/?target=99#code/KYDwDg9gTgLgBAYwgOwM7wEbAGbWABSgEtl4BeOAHgBUAaAPgAoiATALjmoEoPq4z6cVgChQkWIhTo4AQ2wxgUQiXJVqTVrx6d+g1kA

🙂 Expected behavior

When generic type parameters are used in .tsx files, the list must end with , to disambiguate the syntax from jsx opening tag

Additional information about the issue

See also #15713

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions