DEV Community

Discussion on: TypeScript Might Not Be Your God: Case Study of Migration from TS to JSDoc

Collapse
 
trusktr profile image
Joe Pea

You can export a type without making a variable:

/**
 * This type is automatically a type-only export.
 * @typedef {Foo | Bar} Something
 */
Enter fullscreen mode Exit fullscreen mode

This automatically exports the type.

With TS pre 5.5, you can import it like this in another file:

/** @typedef {import('./Something').Something} Something */
Enter fullscreen mode Exit fullscreen mode

With TS 5.5 and above, you can import with JSDoc @import syntax:

/** @import {Something} from './Something' */
Enter fullscreen mode Exit fullscreen mode

Basically just wrap an import statement with /**@ and */ to convert it to type-only import comment.

If you want to avoid @private, you can use official JS private syntax:

class Foo {
  /** @type {number[]} */
  #foo = []
}
Enter fullscreen mode Exit fullscreen mode

Also check out some proposals for simplified and more concise type comment syntax here:

github.com/microsoft/TypeScript/is...

For example see how concise this is compared to JSDoc:

//: abstract
export class Foo { //:<T extends object>
  foo = "456"

  //: abstract
  method() {} //: T
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
what1s1ove profile image
Vladyslav Zubko • Edited

Hey @trusktr ! Thank you for your answer and advice!

I knew about auto-import when the type is declared via JSDoc comments and also about the new @import feature (I followed and contributed to the discussion on this feature here). However, I prefer the type declaration using let + JSDoc comments, as shown in the screenshots above. The main issue with using comments is that there are no ESLint rules to lint them. It's easy to forget to delete something because rules like "no-unused-vars" or "sorted-imports" don't work for type declarations and imports in JSDoc comments.

The issue about annotations as comments is really good! I wasn't aware of it. I've subscribed to it and will follow all the discussions. Thank you!