1

If I write in plain JavaScript, I know I can currently place a sibling .d.ts file next to my .js file in order to type it for use in TypeScript.

Is it possible to write only a .js file and place the declarations in there instead of having separate .d.ts files?

I know currently we can write jsdoc-style comments, and get some typing, but it's fairly limited compared to actual TypeScript. I'd love to write normal declarations inside the .js files.

trusktr
  • 44,284
  • 53
  • 191
  • 263

1 Answers1

1

Although the TypeScript is considering it, it's not possible as of now. Only *.ts files offer the full power of TypeScript.

You could, hypothetically, define all your modules in a single declaration file, but at this point, it will probably be easier to just use TypeScript instead of JavaScript.

If that's beyond your control, the only thing that comes to mind is creating a custom transformer with TypeScript API. Since type definitions are not valid JavaScript and using them inside a .js file would cause a syntax error, you would still need to put them in a comment.

Karol Majewski
  • 23,596
  • 8
  • 44
  • 53
  • It's not out of my control, but I can do things in JS that are very hard to do in TypeScript. F.e., I'm still learning how to solve this one: https://stackoverflow.com/questions/50899400. I want to generate classes with private and protected members based on object literals. My package "lowclass" does this for runtime JS: https://github.com/trusktr/lowclass. So I thought, instead of trying to type the class factory in order to use `Class()` in a TS project, maybe I could just use `Class()` and then write simple type defs, as writing a class with `private` and `protected` members is easy. – trusktr Jan 02 '19 at 06:42
  • In short, arguably figuring out how to do https://stackoverflow.com/questions/50899400 (with additional private and protected members) seems more difficult than just writing some JS with a simple accompanying `class` declaration. If they could live in the same file that'd be sweet! – trusktr Jan 02 '19 at 06:49