TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

Clarify the pros and cons and the use cases for named export vs default export.

Open shaunluttin opened this issue 8 years ago • 2 comments

Challenge

Both myself and my team have experienced some confusion around choosing between named exports and default exports.

On the one hand, official documentation suggests favoring export default.

The TypeScript handbook's page on Modules states:

If you’re only exporting a single class or function, use export default.

One conclusion of the ES Discuss module import topic is that:

The syntax should still favor default import.

On the other hand, prominent projects in the community favor a named export.

The TypeScript Deep Dive book has a page entitled "Avoid export default".

Angular makes heavy use of *.ts files that have a single export class or a single export function, which is in contrast with one of the red flags in the TypeScript handbook's page on Modules.

Suggestion

Create a new page in the handbook that focuses on choosing between a named and a default export.

  1. enumerate the pros and cons of named exports and default exports,
  2. enumerate the use cases for named exports and for default exports, and
  3. explain the concepts behind the existence of each.

shaunluttin avatar Aug 26 '17 21:08 shaunluttin

I can not speak for other documentation authors, or other teams using TS. all what i can take to is the intentions behind this handbook.

The handbook is meant as an introduction to TS/JS features; it is not meant to be a definitive style guide for TS code. using default export or not is mostly a style question to me. We did not produce a style guide intentionally. we understand that the JS community already has enough guidance when it comes to style; and TS is just JS. so our recommendation, use the style guide that fits you and your organization.

mhegazy avatar Aug 28 '17 19:08 mhegazy

I would like to see the wording here changed. The TypeScript Handbook is not presented as a styleguide but rather as documentation.

The wording If you’re only exporting a single class or function, use export default. is authoritative and does not explain any of the cons of using default exports, such as the lack of discoverability and the lack of constraints on the name when importing.

Jameskmonger avatar Aug 31 '18 10:08 Jameskmonger