SyntaxError when TypeScript casting
See original GitHub issueYour Environment
- prettier-plugin-sort-imports version: 3.1.1
- Prettier version: 2.4.1
- node version: 16.9.1
- package manager: npm@7
- IDE: CLI
Describe the bug
When casting in TypeScript with the <> operator, prettier-plugin-sort-imports makes prettier fail with SyntaxError. Searching through closed issues, I found this which looks similar #45 But it appears to not be completely fixed, since I am using version 3. I tried uninstalling prettier-plugin-sort-imports and prettier ran just fine. Reinstalling it again, and the error resumed.
To Reproduce
npx prettier -c test.ts
test.cs:
const value = <string>('');
test.cs with a workaround and an explanation for why <> casting is necessary:
interface ExternalInterface {
test(): Promise<string | number>;
}
class MyImplementation implements ExternalInterface {
public async test(): Promise<string | number> {
return 'foo';
}
}
export async function run() {
const instance = new MyImplementation();
const value = <string>( // breaks prettier
await instance.test()
);
const workaround = (
await instance.test()
) as string; // works, but now the type is far away from the variable definition, especially for multiline calls
}
Expected behavior
Prettier checks the formatting.
Configuration File (cat .prettierrc, prettier.config.js, .prettier.js)
.prettierrc.yaml:
singleQuote: true
printWidth: 100
trailingComma: all
xmlWhitespaceSensitivity: ignore
importOrder:
- '^@foo-.*$'
- '^[./]'
importOrderSeparation: true
importOrderSortSpecifiers: true
overrides:
- files: '*.jmx'
options: { 'parser': 'xml' }
Error log
Single line test.ts: Checking formatting… test.ts[error] test.ts: SyntaxError: Unterminated JSX contents. (1:22)
Larger test.ts: Checking formatting… test.ts[error] test.ts: SyntaxError: Unterminated JSX contents. (13:24)
There may be two issues… Before I recreated this with the example code above, it failed with a different message on our actual code (but still on lines that did <> casting):
Checking formatting… redacted.ts[error] redacted.ts: SyntaxError: Unexpected token (79:2)
Contribute to @trivago/prettier-plugin-sort-imports
- I’m willing to fix this bug 🥇
Issue Analytics
- State:
- Created 2 years ago
- Reactions:3
- Comments:8

Top Related StackOverflow Question
@StringKe, I had the same issue which I fixed by incorporating @byara’s solution into an override for only
.tsfiles ie.The reason is due to a technical limitation of babel when mixing the ‘jsx’ and ‘typescript’ plugins and is documented here
Have you tried to add
typescriptinimportOrderParserPlugins?Reason is, you are using typescript and the content of this file you are formatting is passed to Babel parser. With adding that option you let babel know it is facing TS.