Building a library in TS to be called by TS and JS code and wondering how people hide internal methods and fields. Java has package visibility to handle this. Lacking that in TS, I see two options:
Define interfaces to only expose certain members. But this involves duplicating the definitions and extra code to cast arguments from interface to implementation types.
Put an @private doc comment on the internal members. Possibly exclude such from generated docs.
Note: the private qualifier is NOT a solution, as it only allows code from the same class access. I am talking about the need to access fields from other classes in the same library, but preventing access from clients of the library. That is what Java's package access does.
private
modifier that can be used on ES6/TypeScriptclass
es. At compile time, TypeScript gives you an error when trying to accessprivate
members, but at runtime they are still accessible. (See typescriptlang.org/Handbook#classes, especially the 'Understanding private' section) – Semifluidprivate
, but more of an internal/package access. As JavaScript wasn't designed that way, what you want to do would require some third-party JavaScript library to enforce access to members at runtime. TypeScript, and any of its typing constraints, do not exist at runtime. – Semifluid.d.ts
) file, in which I include only the root module. This way, anything residing in a sub-module ends up being effectively internal. (vice-versa, if your sub-modules are public, move your internal members to a specific sub-module and exclude that from your declaration-build.) – Neilson