You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Namespaces are not being removed from TypeScript! See comments downthread.
Reacted by Leonardo Montenegro, Vasile Pește, Joseph Garrone, Alex Prokhorov, Nuno Miguel, Ailrk, aesyondu, Volodymyr Savchuk, Escape0707, Gareth Jones and 29 more
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.
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.
Yes, I think Wesley Wolfe (@Wolvereness) captured my intent accurately - in other words, Babel probably shouldn't drastically re-architect itself to support namespaces.
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.
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.
Reacted by Jonathan, Titian Cernicova-Dragomir, Daniel Rosenwasser, David Bimamisa, Vasile Pește, Joseph Garrone, Alex, Jonathan Cantrell, eoarch, Nelson Martell and 40 more
Reacted by Jonathan, Titian Cernicova-Dragomir, Frederic Barthelemy, eoarch, resynth1943, Taylor Brown, Yuchen Zhong, Max Poliakov, heedo, Tiven Wang and 3 more
Reacted by Sergey Egorov, Max Heiber, eoarch, shinout, resynth1943, Abbas Monfared, Taylor Brown, Julian Schmidt, heedo, я котик пур-пур and 9 more
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).
Reacted by KittenWithHerbs, Max Heiber, archas, Linus Unnebäck, Seva Golovanov, Yuchen Zhong, ExE Boss, John Stewart, Tiven Wang, Rich Watts and 2 more
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)
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).
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.
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:
classC{}namespaceC{interfaceI{}}consti: C.I=/**/;
Reacted by Roman Šimík, heedo, Andre Z. Sanchez, aosq, FlowIT-JIT, Michał Simka, Maksim, Zames Chua and Harsh Rohila
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.tsnamespacePricing{exportclassCalculator{exportfunctionmethodIWantPublic{...}functioncalculatorMethodAvailableOnlyInNamespace{constresult=helperMethodAvailableOnlyInNamespace();}}}// pricing-utils.tsnamespacePricing{classUtils{functionhelperMethodAvailableOnlyInNamespace{...}// lots of other methods I don't want to be used outside of Pricing}}// consumer-code.tsclassSomeNonPricingSpecificClass{constresult=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?
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.
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?
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".
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.
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.
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.
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?
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.
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...
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.
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.
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!
Reacted by Jirka Dell'Oro-Friedl, Nelson Martell, Pedro Muro, fonlow, James Hinderks and 김회준
Reacted by Jordan Dobson
Reacted by fonlow, James Hinderks, Wojtek Ossowski and 김회준
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.
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.
Reacted by Alex Kizer, James Hinderks, Wojtek Ossowski, 김회준 and Ali Sabtan
Activity
Wolvereness commentedon Apr 17, 2019
Daniel Rosenwasser (@DanielRosenwasser) Was quoted saying:
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.
ChuckJonas commentedon Apr 17, 2019
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:
MartinJohns commentedon Apr 17, 2019
The TypeScript goal 11 states:
So I would not expect them to go away.
RyanCavanaugh commentedon Apr 17, 2019
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.
DanielRosenwasser commentedon Apr 17, 2019
Yes, I think Wesley Wolfe (@Wolvereness) captured my intent accurately - in other words, Babel probably shouldn't drastically re-architect itself to support
namespaces.[-]Are namespaces legacy[/-][+]Are namespaces legacy?[/+]Jonatthu commentedon May 9, 2019
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.
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
RyanCavanaugh commentedon May 13, 2019
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.
weswigham commentedon May 13, 2019
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).dragomirtitian commentedon May 13, 2019
Wesley Wigham (@weswigham) Is
namespacemerging withclass,functionandenuma '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)
weswigham commentedon May 13, 2019
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
staticor 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).zijianhuang commentedon Jun 12, 2019
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.
shrinktofit commentedon Sep 23, 2019
For our team, we can stop to use namespace once if
public type T =andpublic 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:nelson6e65 commentedon Dec 30, 2019
Extension methods (C#) are missed in TypeScript. 😅
10 remaining items
evanmcd commentedon Aug 24, 2022
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).
Is there a way to do this on the server with ES6 Modules? What’s the benefit to that approach vs this one?
DanielRosenwasser commentedon Aug 24, 2022
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.
emcdaniel-sungage commentedon Aug 24, 2022
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?
DanielRosenwasser commentedon Aug 24, 2022
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-utilsthat isn'tfoo.tsitself, then it gives that same sort of "code smell".There are variations of this, but that's about it.
If you have multiple projects, you can control the exposed API shape with
--stripInternalor 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 theexportsfield - 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.
zijianhuang commentedon Aug 24, 2022
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.
ekalkutin commentedon Aug 25, 2022
Could you give any thoughs about that #30994 (comment) ?
emcdaniel-sungage commentedon Aug 28, 2022
Good points fonlow (@zijianhuang).
Daniel Rosenwasser (@DanielRosenwasser) My understanding is that, in my namespace example above, the
Pricing.Calculator.calculatorMethodAvailableOnlyInNamespacemethod would not be available toSomeNonPricingSpecificClass(which is not in the pricing namespace) while in your modules example anything infoo-utilsthat was needed infoo.tswould have to be exported and thus available to any other code in the system. Is that not the case?nvlled commentedon Oct 2, 2022
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.
JirkaDellOro commentedon Nov 16, 2022
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.
maxpatiiuk commentedon Aug 8, 2023
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.
kizerkizer commentedon Dec 9, 2024
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!
nelson6e65 commentedon Dec 14, 2024
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.
This is useful when you have a lot of models and want to use some in the same file. If you export the
defaultedfunction directly as module, you will have to add alias to each import (or name them likedefaultedUserData,defaultedDocumentData, etc) loosing consistency.RyanCavanaugh commentedon Feb 4, 2025
Qtreeview stop doing that or you'll be blocked from the org