Skip to content

Are namespaces legacy? #30994

Closed
Closed

Description

Sorry... I know it specifically says not to ask questions here... but I don't want the opinion of random developers on stack exchange... I want to hear from the typescript team directly.

Are namespaces (aka internal modules) legacy and going away?

There is a discussion about Babel7 support for namespaces . One of the arguments for not supporting them is that they are going away in the future anyways. However, I can't seem to find any mention to that in official documentation.

If that is the case, then it really should be mentioned somewhere... Lots of people are relying on them for libraries (because they provide some very convenient features; especially around code generators).

I personally have at least 10 production projects that would need to be heavily refactored if they went away.

FYI Daniel Rosenwasser (@DanielRosenwasser) (because you were quoted as saying they were legacy).


Response from TypeScript Team (Ryan Cavanaugh (@RyanCavanaugh))

Namespaces are not being removed from TypeScript! See comments downthread.

Activity

  1. Wolvereness commented on Apr 17, 2019

    @Wolvereness

    Daniel Rosenwasser (@DanielRosenwasser) Was quoted saying:

    ... namespaces are not a huge loss ...

    Which from my interpretation meant that it's not a priority for a system to support namespaces, but nothing to the effect of implicating their deprecation or legacy status.

    Joe Haddad (@Timer) was quoted saying they were legacy, which could only be substantiated using third party opinion blog posts.

  2. ChuckJonas commented on Apr 17, 2019

    @ChuckJonas
    Author

    Wesley Wolfe (@Wolvereness) sorry yes, didn't mean to put words in Daniel Rosenwasser (@DanielRosenwasser) mouth. His quote was used to argue that they are legacy...

    Here's the full post for clarity:

    TypeScript PM here. Broadly speaking, I feel that

    namespaces are not a huge loss; the React community is firmly on-board with ES modules anyway, and that's the direction the TypeScript world is taking.
    const enums are often misused. Sure, they can be great for the internals of a library to get some speed improvements, but they generally shouldn't be used outside of that scope.
    Merging behavior is marginally useful now that TypeScript 3.1 has the ability to tack properties onto functions. The fact that enums merge is also something I've never seen used out in the wild.
    Anyway, Ryan Cavanaugh (@RyanCavanaugh) might have some thoughts here too.

  3. added
    Discussion
    on Apr 17, 2019
  4. MartinJohns commented on Apr 17, 2019

    @MartinJohns
    Contributor

    The TypeScript goal 11 states:

    Do not cause substantial breaking changes from TypeScript 1.0.

    So I would not expect them to go away.

  5. RyanCavanaugh commented on Apr 17, 2019

    @RyanCavanaugh
    Member

    I guess you're referring to babel/babel#8244 (comment) ? This person isn't a TypeScript team member and I don't know where they got that idea.

    We've never removed any syntax from the language since 1.0 and don't intend to do so in the future.

  6. DanielRosenwasser commented on Apr 17, 2019

    @DanielRosenwasser
    Member

    Yes, I think Wesley Wolfe (@Wolvereness) captured my intent accurately - in other words, Babel probably shouldn't drastically re-architect itself to support namespaces.

  7. changed the title [-]Are namespaces legacy[/-] [+]Are namespaces legacy?[/+] on Apr 17, 2019
  8. Jonatthu commented on May 9, 2019

    @Jonatthu

    Ryan Cavanaugh (@RyanCavanaugh) dotansimha/graphql-code-generator#643 (comment)

    Is this really happening on Typescript?
    Is Typescript team deprecating namespaces?
    I think it is really useful for this use case and others that creates multiple types related to a dynamic query such as Graphql gen types.

    import { Action } from '@ngrx/store';
    
    export namespace PermissionsActions
    {
    
    	export const LOAD_DETAILS: string = '[Permissions] Load Details';
    	export const LOAD_DETAILS_FAIL: string = '[Permissions] Load Details Fail';
    	export const LOAD_DETAILS_SUCCESS: string = '[Permissions] Load Details Success';
    
    	export class LoadDetails implements Action
    	{
    		/**
    		 * The type of the action.
    		 */
    		public readonly type: string = LOAD_DETAILS;
    
    		constructor(public permissionKey: string) { }
    	}
    
    	export class LoadDetailsFail implements Action
    	{
    		/**
    		 * The type of the action.
    		 */
    		public readonly type: string = LOAD_DETAILS_FAIL;
    
    		constructor() { }
    	}
    
    	export class LoadDetailsSuccess implements Action
    	{
    		/**
    		 * The type of the action.
    		 */
    		public readonly type: string = LOAD_DETAILS_SUCCESS;
    
    		constructor(public payload: any) { }
    	}
    
    	/**
    	 * Permissions Actions Type Union
    	 */
    	export type Actions =
    		| LoadDetails
    		| LoadDetailsFail
    		| LoadDetailsSuccess
    		;
    
    }
    
    

    Why should we lose this ability?

    I can just import this as

    import { PermissionsActions } from '...';
    vs
    import * as PermissionsActions from '...';

    With namespaces I can find all references easily plus we can maintain the same naming convention when we import this kind of types on a ts file.

    Really useful on Angular Applications using NGRX and now applications using Graphql Types Generation.

    FredyC

  9. RyanCavanaugh commented on May 13, 2019

    @RyanCavanaugh
    Member

    Jonathan (@Jonatthu) I'd refer you to my comment upthread. Again: We've never removed any syntax from the language since 1.0 and don't intend to do so in the future.

    For anyone reading this thread: Please don't trust internet randos about TypeScript's feature plans! Our roadmap is public anyone saying crazy stuff like that should be able to point to a roadmap entry for it.

  10. weswigham commented on May 13, 2019

    @weswigham
    Member

    Namespaces are probably never going away and, simultaneously, you probably shouldn't use them, since better, more standard and modern patterns exist through the use of modules. If you have code that you feel needs to use a namespace, more power to you and go for it, but most of the time you don't need one, as we now have a different conceptual organizational model recommended for large-scale JS (modules). That's why Daniel Rosenwasser (@DanielRosenwasser) said namespaces are not a huge loss - most new TS code should probably never need to use them, and should think hard about if they really need to.

    Minimally, we'll never outright remove namespaces because they're incredibly useful for describing type hierarchies and the like of existing cjs libraries - it's just that modern esm-like code probably doesn't need them, since the module itself is a namespace (where nesting is achieved thru reexports).

  11. dragomirtitian commented on May 13, 2019

    @dragomirtitian
    Contributor

    Wesley Wigham (@weswigham) Is namespace merging with class, function and enum a 'good' use of namespaces? (as described in the docs)

    I ask because people seem afraid of namespaces these days for some reason and the merging functionality can't easily be achieved by other means. (Functions have nicer semantics these days for adding members, but aside from that)

  12. weswigham commented on May 13, 2019

    @weswigham
    Member

    Is namespace merging with class, function and enum a 'good' use of namespaces?

    Sometimes - since we can't recognize ad-hoc attachments of certain kinds of static properties, it might be warranted - in many cases an ad-hoc property on a function or a class static will suffice (unless you need it to contain types), though. Although it's just as valid to question if you really needed the merge to begin with - if, for example, you want to associate a component and its argument type, isn't exporting both of them from the same module sufficient? Why also wrap them in a namespace? There's no point there.

    It comes down to this:
    If you're considering using namespaces for code organization: Don't. Modules have subsumed that role.
    If you need functionality that only namespaces can provide: Do, but check that it's not equally expressive to express the concept without a namespace (eg, with a class static or function property, or reexported module). It is also bad style to mix namespaces and modules in the same project - it just feels off, since one of the major features of namespaces in the traditional sense is cross-file scope merging, which doesn't occur across modules (since, as I said, the module itself is actually a namespace).

  13. zijianhuang commented on Jun 12, 2019

    @zijianhuang

    I had read the comments at babel/babel#8244 made by the Babel team as mentioned above.

    Complex business fat clients like SPA may contain a lot types in different namespaces. ES module is not going to replace namespaces of TS, since module is 1 to 1 mapping with file. Manually avoiding circular references among files is a nightmare against application programming and overall productivity of app programmers. Namepaces is the best solution for code generation -- all generated by code generator stay in one file.

    All types from such generated file are with the namespace prefix, so app programmers could easily tell which types are from generated lib.

    I am building a complex business app of Angular SPA with tons of types mapped to the server types of .NET backend. Having namespaces is great for productivity.

    And the good thing is, the Babel team may be changing their mind about supporting namespaces: babel/babel#9785
    So much thanks to Wesley Wolfe (@Wolvereness).

    Hopefully this will be available in next release.

  14. shrinktofit commented on Sep 23, 2019

    @shrinktofit

    Why also wrap them in a namespace?

    For our team, we can stop to use namespace once if public type T = and public interface I {} is allowed in class scope. Because sometimes we don't want to expose interfaces/types directly into module scope. Only choice is to use namespace merging:

    class C { }
    namespace C {  interface I { }  }
    
    const i: C.I = /**/ ;
  15. nelson6e65 commented on Dec 30, 2019

    @nelson6e65

    Wesley Wigham (@weswigham) Is namespace merging with class, function and enum a 'good' use of namespaces? (as described in the docs)

    Extension methods (C#) are missed in TypeScript. 😅

  16. 10 remaining items

  17. evanmcd commented on Aug 24, 2022

    @evanmcd

    I’m trying to understand why namespaces shouldn’t be used to improve encapsulation, such as the following case in which I have some complex functionality in a server-side app that I want to spread across multiple files, and want to make public only a small subset of the members that should be available to other members of the namespace.

    (and forgive me if the code is not 100% correct - I’ve never actually used namespaces, I’m just looking into whether I should or not).

    // calculator.ts
    namespace Pricing {
    	export class Calculator {
    		export function methodIWantPublic {...}
    		function calculatorMethodAvailableOnlyInNamespace {
    			const result = helperMethodAvailableOnlyInNamespace();
    		}
    	}
    }
    
    // pricing-utils.ts
    namespace Pricing {
    	class Utils {
    		function helperMethodAvailableOnlyInNamespace {...}
    		// lots of other methods I don't want to be used outside of Pricing
    	}
    }
    
    // consumer-code.ts
    class SomeNonPricingSpecificClass {
    	const result = Pricing.methodIWantPublic();
    }

    Is there a way to do this on the server with ES6 Modules? What’s the benefit to that approach vs this one?

  18. DanielRosenwasser commented on Aug 24, 2022

    @DanielRosenwasser
    Member

    If you are using ES6 modules, you just don't export the things you don't want to share. It works the same way if I'm understanding the question correctly.

  19. emcdaniel-sungage commented on Aug 24, 2022

    @emcdaniel-sungage

    Daniel Rosenwasser (@DanielRosenwasser) thanks for the reply. But how would that work with local modules (not on NPM) that have multiple files? How would I keep the consumer code from being able to access a method in a helper (for example) that another file in the module needed access to?

  20. DanielRosenwasser commented on Aug 24, 2022

    @DanielRosenwasser
    Member

    You could create a folder that provides utilities for a module. The module can pick-and-choose what it wants to export. If something imports from foo-utils that isn't foo.ts itself, then it gives that same sort of "code smell".

    src/
    ├── foo-utils/
    │   ├── util1ForFoo.ts
    │   ├── util2ForFoo.ts
    │   └── util3ForFoo.ts
    └── foo.ts
    

    There are variations of this, but that's about it.

    If you have multiple projects, you can control the exposed API shape with --stripInternal or API Extractor. If you're using npm packages with Node 12 and later, you can even control which files are reachable from within a package using the exports field - which is actual runtime controlled encapsulation.

    There's a bunch of options, and at the end of the day your namespaces didn't give any more encapsulation than modules without those options. Someone can always reach into a namespace and grab an exported function - it's just that maybe it seemed suspicious to do so.

    If at the end of the day you still want to use namespaces, that's fine. TypeScript won't be removing them any time soon, though just be aware that you're swimming against the current these days. The broader community is not leveraging them anymore, and not all tooling may choose to put in the work to support them.

  21. zijianhuang commented on Aug 24, 2022

    @zijianhuang

    Bernardo (@be) aware that you're swimming against the current these days. The broader community is not leveraging them anymore, and not all tooling may choose to put in the work to support them.

    Be aware which current you are in. A few years ago, The Babal's team had made up their mind not to support namespace, however, eventually they had changed their mind and supported namespace at babel/babel#9785 .

    Yes, it is technically possible that you can survive with modules only and without namespace even in developing complex business applications with multiple layers, tiers and brokers, just as you can survive with structural programming without OOP. However, it is more viable to have namespaces, kind of managed complexity, for managing unmanaged complexity. With namespaces, some dev tools could be easier to develop, for example, service to client code generators, and the codes generated are overall much better. So application developers could live better.

  22. ekalkutin commented on Aug 25, 2022

    @ekalkutin

    Bernardo (@be) aware that you're swimming against the current these days. The broader community is not leveraging them anymore, and not all tooling may choose to put in the work to support them.

    Be aware which current you are in. A few years ago, The Babal's team had made up their mind not to support namespace, however, eventually they had changed their mind and supported namespace at babel/babel#9785 .

    Yes, it is technically possible that you can survive with modules only and without namespace even in developing complex business applications with multiple layers, tiers and brokers, just as you can survive with structural programming without OOP. However, it is more viable to have namespaces, kind of managed complexity, for managing unmanaged complexity. With namespaces, some dev tools could be easier to develop, for example, service to client code generators, and the codes generated are overall much better. So application developers could live better.

    Could you give any thoughs about that #30994 (comment) ?

  23. emcdaniel-sungage commented on Aug 28, 2022

    @emcdaniel-sungage

    Good points fonlow (@zijianhuang).

    at the end of the day your namespaces didn't give any more encapsulation than modules without those options.

    Daniel Rosenwasser (@DanielRosenwasser) My understanding is that, in my namespace example above, the Pricing.Calculator.calculatorMethodAvailableOnlyInNamespace method would not be available to SomeNonPricingSpecificClass (which is not in the pricing namespace) while in your modules example anything in foo-utils that was needed in foo.ts would have to be exported and thus available to any other code in the system. Is that not the case?

  24. nvlled commented on Oct 2, 2022

    @nvlled

    I'm in agreement that namespaces have valid use cases. In addition to the points given above (converting namespaces to modules could break encapsulation), my reason is that I would like to keep related code properly encapsulated together as much as possible, and would rather avoid having them split and cluttered across many files.

  25. JirkaDellOro commented on Nov 16, 2022

    @JirkaDellOro

    I've experienced many times that people like myself struggle a lot with ts-namespaces and es-modules, especially when it comes down to try to work with both in the same project. I did some "structured" fiddling and found that on the Javascript-side after compilation, things appear to be quite simple, but can't be done in a standard way with typescript before compilation.

    I wrote about it here and I'd be happy to see some comments on that before I start creating a plugin or extension, that tweaks the compiled output. I expect to be missing some important parts...

    https://jirkadelloro.github.io/TS-Namespaces-ES-Modules/

    A student of mine struggled again using namespaces and modules together. I don't see the point why this can't be done out of the box. Referring to my article, it would be nice to hear from the TypeScript-Team to understand what I'm missing.

  26. maxpatiiuk commented on Aug 8, 2023

    @maxpatiiuk

    Note, module declarations, and module expressions may come to ECMAScript in a few years - those should be able to further replace some use cases for namespaces mentioned earlier in this thread.

  27. kizerkizer commented on Dec 9, 2024

    @kizerkizer

    It's silly that namespaces in TS are (as I've found out) evidently "frowned upon". It's like one of those countless no no's that dogmatically permeate software development. Namespaces are ultimately just for names (shockingly). They are a natural organizational facility for identifiers. That's why so many languages have them.

    They don't have to compete with ES modules, they can compliment them. Though ES imports offer aliasing the core issue is that ES modules being designed for JS, a dynamically typed language, are about exporting/importing values. With values you can implement namespacing with regular objects, just setting properties to values and so on. But you cannot handle a type this way because it is not a value nor existent at runtime. In this case we can use TypeScript namespaces.

    Don't listen to the haters TypeScript! Namespaces forever!

  28. nelson6e65 commented on Dec 14, 2024

    @nelson6e65

    I use namespaces to extend some interfaces. For example, add functions to normalize and transform data.

    As we know, interfaces are just types: they will not generate runnable code on runtime. But, if you add a namespace with the same name, in the same file, you can export functions that you can call as a static method of an interface.

    export interface IUserData {
      // ...
    }
    
    export namespace IUserData {
      export const defaulted = (data: Partial<IUserData> = {}): IUserData => ...
    }
    import { IUserData } from '@/data/user.data.ts';
    
    // ...
    
    IUserData.defaulted(reponse.data);

    This is useful when you have a lot of models and want to use some in the same file. If you export the defaulted function directly as module, you will have to add alias to each import (or name them like defaultedUserData, defaultedDocumentData, etc) loosing consistency.

  29. RyanCavanaugh commented on Feb 4, 2025

    @RyanCavanaugh
    Member

    Qtreeview stop doing that or you'll be blocked from the org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Discussion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions