Title: Suggestion: Module level privacy for types · Issue #15465 · microsoft/TypeScript · GitHub
Open Graph Title: Suggestion: Module level privacy for types · Issue #15465 · microsoft/TypeScript
X Title: Suggestion: Module level privacy for types · Issue #15465 · microsoft/TypeScript
Description: Module level privacy for types It is sometimes useful to declare a type within a module and then have that module handle all of the operations on that type. This way the consumers of the module will not know the internals of the type and...
Open Graph Description: Module level privacy for types It is sometimes useful to declare a type within a module and then have that module handle all of the operations on that type. This way the consumers of the module wil...
X Description: Module level privacy for types It is sometimes useful to declare a type within a module and then have that module handle all of the operations on that type. This way the consumers of the module wil...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/15465
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Suggestion: Module level privacy for types","articleBody":"# Module level privacy for types\r\n\r\nIt is sometimes useful to declare a type within a module and then have that module handle all of the operations on that type. This way the consumers of the module will not know the internals of the type and cannot couple themselves to its properties. But we still get type safety when calling the module's functions. This is especially useful in a FP programming style where we only use functions and types packaged into modules.\r\n\r\n## Goals\r\n\r\nTo make the internal of types private to the module they are declared in.\r\n\r\n## Non-goals\r\n\r\nTo introduce nominal typing in order to solve the goal.\r\n\r\n## Example scenario\r\n\r\nConsider a `date.ts` module that handles a `Date` type. The internals of the `Date` type is private to the `date.ts` module. This is declared by a `module` modifier on the `Date`'s members that this suggestions adds support for. But the type is still exported so other modules know of the `Date` type. This means type-safety is possible when calling the methods of the Date module.\r\n\r\ndate.ts\r\n\r\n```typescript\r\nexport interface Date { \r\n module readonly day : number,\r\n module readonly month : number,\r\n module readonly year : number\r\n};\r\n\r\nexport function createDate(day: number, month: number, year: number): Date {\r\n return {day, month, year};\r\n}\r\n\r\nexport function diffYears(date1: Date, date2: Date): number {\r\n return dat1.year - date2.year\r\n}\r\n\r\nexport function year(date: Date): number {\r\n return date.year;\r\n}\r\n```\r\n\r\nConsumption\r\n\r\n```typescript\r\nimport * as Date from \"./date\";\r\n\r\nconst date1 = Date.createDate(2017, 1, 1);\r\nconst date2 = Date.createDate(2018, 1, 1);\r\nconst year = Date.year(date);\r\nconst diff = Date.diffYears(date1, date2);\r\n// This will give an error because the year property is private to date.ts\r\nconst year = date.year; \r\n```\r\n## Usefulness\r\n\r\nUsing this approach it will become much easier to refactor the `Date` type. Let's say we decide it is better to have it store ticks since epoch:\r\n\r\n```typescript\r\nexport interface Date { \r\n module readonly ticks : number,\r\n};\r\n```\r\n\r\nWithout privacy, other modules may have directly read the `Date.years` property instead of going through our `year()` function making our refactoring hard. \r\n\r\n## Similar features in other languages\r\n\r\nOcaml: [abstract type](https://ocaml.org/learn/tutorials/modules.html)\r\nReason: [abstract type](https://youtu.be/24S5u_4gx7w?t=1231)\r\nElm: [opaque type](http://stackoverflow.com/questions/40794368/what-is-an-opaque-type-in-elm-and-why-is-it-valuable)\r\nF#: [signature files](http://msdn.microsoft.com/en-us/library/dd233196.aspx)\r\nHaskell: [export lists](http://www.haskell.org/onlinereport/modules.html)\r\n\r\n## Work-arounds\r\n\r\n### Class\r\nIt has been noted that in typescript `class` can be used to emulate the idea of this proposal. But that is only true because typescript adds the `private` modifier to `class`. In plain JS/ES it would not make sense to use both a module and a `class` as modules alone provides an idiomatic construct for packaging static functions together. So using `class` in plain JS would only add another level of nesting/complexity/syntax without adding any value.\r\n\r\nConsider this plain JS/ES module:\r\n\r\ndate.js\r\n\r\n```js\r\n/**\r\n* @param {number} day\r\n* @param {number} month\r\n* @param {number} year\r\n* @returns {Date}\r\n* NOTE: Return type is to be considered immutable and opaque.\r\n*/\r\nexport function createDate(day, month, year) {\r\n return { day, month, year };\r\n}\r\n\r\n/**\r\n* @param {Date} date \r\n* @returns {number}\r\n*/\r\nexport function year(date) {\r\n return date.year;\r\n}\r\n```\r\n\r\nIn the above module it does not make sense to use `class` because in JS `class` is neither immutable nor has the ability to be opaque. Typescript currently has the ability to express all the notes in the comments except the \"considered to be opaque\" part. For example \"considered to be immutable\" could be expressed as `readonly` on the type's properties. This proposal is about being able to express the \"considered to be opaque\" part in the typescript type system without having to modify the original JS program to use `class`.\r\n\r\nAnother big disadvantage of using `class` as a data record is that it cannot survive `JSON.stringify()`, `JSON.parse()` round-trips. This makes `class` impractical to use in many real-world scenarios such as for types in a serializable [Redux](https://github.com/reactjs/redux) state, or any types you want to put in local storage, or send over the network.\r\n\r\nThe closest `class` work-around that is available in TS today is what @gcnew describes [here](https://github.com/Microsoft/TypeScript/issues/15408#issuecomment-297929131). This example also survives round-trips. However it requires us to declare a class and take special care to not use all class features. It also requires code to re-export all the class methods from the module. So it involves quite a lot of syntatic work-around noise compared to the idiomatic JS example above. This suggestion makes it possible to write idiomatic JS instead of adjusting the JS to fit the current privacy features in TS.\r\n\r\n### Prefix\r\nAnother suggested work-around is to prefix the fields in the record with `_` in order to mark them as internal. This work-around is much better in the sense that it does not alter the way you write the code. But there are two drawback. The first being that obviously this would not enable any compile-time checks. The second being that although `_`is a convention commonly used for private members of a `class` in OOP style programming, there is (AFAIK) no such tradition for FP style record types. So the use of `_` in this case becomes unconventional.\r\n\r\n## Related suggestions\r\n\r\n#321 is an earlier suggestion for the same thing.\r\n\r\nAbstract/opaque types was originally proposed in #15408 which has relevant discussions leading up to this proposal.\r\n\r\nThe `internal` modifier in #5228 is similar. It adds privacy on the package level. If each module was a package and `internal` was available for types in addition to `class` then it would be identical to this suggestion.","author":{"url":"https://github.com/jonaskello","@type":"Person","name":"jonaskello"},"datePublished":"2017-04-29T11:07:33Z","url":"https://github.com/microsoft/TypeScript/issues/15465"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:1f699aed-1bfb-61fd-a04c-48e835e8ee7c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D2DE:EF9BF:59693A:782B11:6B00A9A4 |
| html-safe-nonce | 5a736665b50f03712c3a43884c8c49aadd21b97a8e8181369eb4c6e99881a808 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMkRFOkVGOUJGOjU5NjkzQTo3ODJCMTE6NkIwMEE5QTQiLCJ2aXNpdG9yX2lkIjoiNTc1NTA4NTk4NTAzODExNDkyIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | eff22093da3d4e07ea939de2595fb73bd35b9f1c3bcd0d6dc212cbf5e30019f3 |
| hovercard-subject-tag | issue:225250096 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/15465/issue_layout |
| twitter:image | https://opengraph.githubassets.com/cc2529984ff7cc6af154e4c2b4ed39937ecebdd4c66c69a8442488b38af4d048/microsoft/TypeScript/issues/15465 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/cc2529984ff7cc6af154e4c2b4ed39937ecebdd4c66c69a8442488b38af4d048/microsoft/TypeScript/issues/15465 |
| og:image:alt | Module level privacy for types It is sometimes useful to declare a type within a module and then have that module handle all of the operations on that type. This way the consumers of the module wil... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | jonaskello |
| hostname | github.com |
| expected-hostname | github.com |
| None | 455b493e3402a3a3a06beac5d20bb7db3da060808b220aa48d6a7eca7c59863a |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 2f575159976167242d488c0b062eb355c4e198b7 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width