Title: Proposal: 'typeon' operator · Issue #4640 · microsoft/TypeScript · GitHub
Open Graph Title: Proposal: 'typeon' operator · Issue #4640 · microsoft/TypeScript
X Title: Proposal: 'typeon' operator · Issue #4640 · microsoft/TypeScript
Description: Proposal: 'typeon' operator The typeon operator references the type associated with an interface or class property, but in contrast to typeof, refers to it through the containing Type itself. I.e. directly queries the type set on the pro...
Open Graph Description: Proposal: 'typeon' operator The typeon operator references the type associated with an interface or class property, but in contrast to typeof, refers to it through the containing Type itself. I.e. ...
X Description: Proposal: 'typeon' operator The typeon operator references the type associated with an interface or class property, but in contrast to typeof, refers to it through the containing Type itsel...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/4640
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Proposal: 'typeon' operator","articleBody":"## Proposal: 'typeon' operator\n\nThe `typeon` operator references the type associated with an interface or class property, but in contrast to `typeof`, refers to it through the containing _Type_ itself. I.e. directly queries the type set _on_ the property rather than the type _of_ an instance of it:\n\n``` ts\ninterface MyInterface {\n prop: number;\n}\n\nlet val: typeon MyInterface.prop; // type of val is 'number'\n```\n\nThis would work with any property, including ones contained in anonymous and nested interfaces:\n\n``` ts\ninterface MyInterface {\n obj: {\n x: number;\n y: number;\n }\n}\n\nlet myX: typeon MyInterface.obj.x; // type of myX is now 'number'\n```\n\nGeneric interfaces:\n\n``` ts\ninterface MyInterface\u003cT> {\n obj: {\n x: T;\n y: T;\n func: (arg: T) => T;\n }\n}\n\nlet f: typeon MyInterface\u003cnumber>.obj.func; // type of f is now (arg: number) => number\n```\n\nIt would be possible to reference the property types at any scope, including within the referenced declaration itself:\n\n``` ts\ninterface MyInterface {\n val: string;\n anotherVal: typeon MyInterface.val;\n\n obj: {\n x: number,\n y: number;\n func(arg:number): typeon MyInterface.obj.x;\n }\n}\n```\n## The `this` type reference\n\nA special `this` type reference could be supported for this very purpose. `this` would be scoped to the closest containing interface, and that would also apply to anonymous ones:\n\n``` ts\ninterface MyInterface {\n val: string;\n anotherVal: typeon this.val;\n\n obj: {\n x: number,\n y: number;\n\n // Note: 'this' is scoped to the anonymous interface here. \n // 'typeon this.val' would give an error.\n func(arg: string): typeon this.x; \n }\n}\n```\n\nIt would also be available in interfaces declared through `type` declarations and for purely anonymous ones:\n\n``` ts\ntype MyType = { \n name: string;\n age: number;\n query: (username: typeon this.name) => typeon this.age;\n}\n\nlet test: { x: number, y: typeon this.x }\n```\n\nand to classes, which would also include references to the types of properties declared in base classes when using `this` (a possible extension could also include support for `super`):\n\n``` ts\nclass UserBase {\n id: string;\n}\n\nclass User extends UserBase {\n age: number;\n\n chatWithUser(id: typeon this.id): { id: typeon User.id, age: typeon User.age } {\n\n // The first argument for 'chatWith' is expected to be a string here, so this works.\n chatWith(id); \n ..\n }\n}\n```\n\nIn a class declaration, `typon this` can only be used from instance positions. To reference static members, the name of the class would be used with `typeof` (note: no equivalent `typeof this` or a standalone `this` type is included in this proposal).\n\n``` ts\nclass Example {\n val: number;\n static val: string;\n\n instanceFunc1(): typeon this.val; // OK, resolves to 'number'\n instanceFunc2(): typeof Example.val; // OK, resolves to 'string'\n\n static staticFunc1(): typeon Example.val; // OK, consistent with external references.\n static staticFunc2(): typeof Example.val; // OK, resolves to 'string'\n}\n```\n\nThis was chosen to improve clarity and for consistency with generic classes, where the instantiated values of generic parameters are not available at static positions:\n\n``` ts\nclass Example\u003cT> { // The example is given where T = number\n val: T;\n static val: string;\n\n instanceFunc1(): typeon this.val; // OK, resolves to 'number'.\n instanceFunc2(): typeof Example.val; // OK, resolves to 'string'\n\n static staticFunc1(): typeon Example\u003cnumber>.val; // OK, consistent with external references.\n static staticFunc2(): typeof Example.val; // OK, resolves to 'string'\n}\n\nlet c = new Example\u003cnumber>();\n```\n## Example use cases\n\nUsing these ad-hoc references would make it easier to express of the semantic intention for the usage of the type, and automatically \"synchronize\" with future changes to the type of the referenced property. This both reduces effort and prevents human errors:\n\n``` ts\nclass UserBase {\n // The type for 'id' has now changed, this usually means that all similar \n // semantic usages of it would need to be manually checked and updated, \n // this includes ones in derived classes.\n id: string | number; \n}\n\nclass User extends UserBase {\n age: number;\n\n // The type of the 'id' argument and anonymous interface property has \n // automatically synchronized with the one set in the base class!\n // This ensures that they will always be consistent and will propagate type errors \n // into the body of the function.\n chatWithUser(id: typeon this.id): { id: typeon User.id, age: typeon User.age } { \n\n // The first argument for 'chatWith' is expected to be a string here, \n // but now the type of 'id' has changed to string | number so will error.\n // This compile-time error is possible because the type was referenced with 'typeon'\n chatWith(id); // Error! type 'string' is not assignable from 'string | number'\n ..\n }\n}\n```\n\nAnother effective use is to encapsulate and reference anonymous types within a class or interface declaration without needing to declare additional type aliases or interfaces. This yield a different style of coding:\n\n``` ts\nclass Process {\n id: number;\n\n state: {\n memoryUsage: {\n real: number;\n virtual: number;\n private: number;\n };\n\n processorUsage: Array\u003c{ index: number, percentage: number }>;\n }\n\n constructor() {\n ...\n }\n ..\n}\n\nclass OSQuery {\n static queryMemoryUsage(id: typeon Process.id): typeon Process.state.memoryUsage {\n return { \n real: OS.getRealUsage(id), \n virtual: OS.getVirtualUsage(id), \n private: OS.getPrivateUsage(id)\n };\n }\n\n static queryProcessorsUsage(id: typeon Process.id): typeon Process.state.processorUsage {\n result: typeon Process.state.processorUsage;\n\n for (let i=0; i\u003c OS.processorCount; i++) {\n result.push( { index: i, percentage: OS.getProcessorUsage(id, i) })\n }\n\n return result;\n }\n\n static queryProcessState(id: typeon Process.id): typeon Process.state {\n return { \n memoryUsage: this.queryMemoryUsage(id),\n processorUsage: this.queryProcessorsUsage(id)\n }\n }\n ..\n}\n```\n\nIn the conventional style of coding, 4 auxiliary interfaces or type aliases would need to be declared to achieve this: \n\n``` ts\ninterface ProcessorUsageEntry {\n index: number;\n percentage: number;\n}\n\ninterface MemoryUsage {\n real: number;\n virtual: number;\n private: number; \n}\n\ntype ProcessorID = number; // aliased in case that associated type changes\n\ninterface ProcessState {\n id: ProcessorID;\n memoryUsage: MemoryUsage;\n processorUsage: Array\u003cProcessorUsageEntry>\n}\n```\n## Reusing the syntax to reference a class instance type\n\nIt is also possible to naturally extend the syntax to reference a type that only includes members of a class _instance_ (`typeof MyClass` only gives the type of the constructor):\n\n``` ts\nclass MyClass {\n instanceProp: number;\n static staticProp: string;\n\n constructor(arg: boolean) {\n ..\n }\n}\n\nlet a: typeof MyClass; // 'a' now has type { staticProp: string, new (arg: boolean) }\n\nlet b: typeon MyClass; // 'b' now has type { instanceProp: number }\n```\n## Equivalent reduction to named type aliases\n\nThis can be internally implemented in the compiler like this:\n\nSource:\n\n``` ts\ninterface MyInterface {\n val1: string;\n val2: typeon this.val1;\n val3: typeon this.val2;\n\n obj: {\n x: number,\n y: number;\n\n func(arg: string): typeon this.x; \n }\n}\n```\n\nReduction:\n\n``` ts\ntype TypeOn_val1 = string;\ntype TypeOn_val2 = TypeOn_val1;\ntype TypeOn_val3 = TypeOn_val2;\n\ntype TypeOn_obj_x = number;\ntype TypeOn_obj_func_returnType = TypeOn_obj_x;\n\ntype TypeOn_obj = {\n x: TypeOn_obj_x;\n y: number;\n\n func(arg: string): TypeOn_obj_func_returnType;\n}\n\ninterface MyInterface {\n val1: TypeOn_val1;\n val2: TypeOn_val2;\n val3: TypeOn_val3;\n\n obj: TypeOn_obj;\n}\n```\n\n**Example with generic interfaces**:\nSource:\n\n``` ts\ninterface MyGenericInterface\u003cT> {\n val1: T;\n val2: typeon val1;\n\n obj: {\n a: Array\u003cT>,\n\n func(arg: T): typeon this.a; \n }\n}\n```\n\nReduction (this uses the new [generic type alias declarations](https://github.com/Microsoft/TypeScript/issues/1616) introduced in 1.6):\n\n``` ts\ntype TypeOn_val1\u003cT> = T;\ntype TypeOn_val2\u003cT> = TypeOn_val1\u003cT>;\n\ntype TypeOn_obj_a\u003cT> = Array\u003cT>;\ntype TypeOn_obj_func_returnType\u003cT> = TypeOn_obj_a\u003cT>;\n\ntype TypeOn_obj\u003cT> = {\n a: TypeOn_obj_a\u003cT>;\n\n func(arg: T): TypeOn_obj_func_returnType\u003cT>\n};\n\ninterface MyGenericInterface\u003cT> {\n val1: TypeOn_val1\u003cT>;\n val2: TypeOn_val2\u003cT>;\n\n obj: TypeOn_obj\u003cT>;\n}\n\n```\n## Possible issues and their solutions\n\nDetect and error on circular references:\n\n``` ts\ninterface SelfReferencingPropertyType {\n x: typeon this.x; // Error: self reference\n}\n\ninterface EndlessLoop {\n x: typeon this.y; // Error: indirect self reference\n y: typeon this.x; // Error: indirect self reference\n}\n```\n\nThis would happen automatically through the reduction described above. The error currently reported through `type` is _\"Error: type 'TypeOn_EndlessLoop_y' circularly references itself\"_.\n## Current workarounds\n\nIt is currently possible to partially emulate this using `typeof` with a \"dummy\" instance of the type:\n\n``` ts\ninterface MyInterface {\n obj: {\n x: number,\n y: number\n }\n}\n\nlet dummy: MyInterface;\n\nlet val: typeof dummy.obj;\n\n```\n\nAnd even:\n\n``` ts\ninterface MyInterface {\n obj: {\n x: number,\n y: typeof dummy.obj.x;\n }\n}\n\ninterface AnotherInterface {\n func(arg:number): typeof dummy.obj;\n}\n\nvar dummy: MyInterface;\n```\n\nThough these workarounds requires a globally scoped variable, and not always possible or desirable for use in declaration files. They also cannot support keywords like `this` (or `super`) thus cannot be used within anonymous types.\n\nReferences to generic parameters cannot be emulated:\n\n``` ts\ninterface MyInterface\u003cT> {\n x: T;\n y: typeon this.x; // Not possible to emulate this\n}\n```\n\n[Originally described at #4555]\n","author":{"url":"https://github.com/rotemdan","@type":"Person","name":"rotemdan"},"datePublished":"2015-09-04T14:12:40Z","url":"https://github.com/microsoft/TypeScript/issues/4640"}
| 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:a148ad19-6fe9-9152-bfcd-7a24eb878edc |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | AA7A:DB09F:D198E9:10C6067:6B010562 |
| html-safe-nonce | 96b4c2ac632451a38015b3056a075a7b64a9897c4276d0d35bb1f50eaf1973b8 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBQTdBOkRCMDlGOkQxOThFOToxMEM2MDY3OjZCMDEwNTYyIiwidmlzaXRvcl9pZCI6IjkwNjMyMzAxNTAwNDQzNTM4OTAiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | ea4abcd6bcc3f89a42142f4205ad229f4d50b0a8f3826852e0279a62f832f0a4 |
| hovercard-subject-tag | issue:104898491 |
| 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/4640/issue_layout |
| twitter:image | https://opengraph.githubassets.com/6ec58636a6cbcf93a1300918e5cd49fe51391f9a3f198ade8cee1a1292bc8ec3/microsoft/TypeScript/issues/4640 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/6ec58636a6cbcf93a1300918e5cd49fe51391f9a3f198ade8cee1a1292bc8ec3/microsoft/TypeScript/issues/4640 |
| og:image:alt | Proposal: 'typeon' operator The typeon operator references the type associated with an interface or class property, but in contrast to typeof, refers to it through the containing Type itself. I.e. ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | rotemdan |
| hostname | github.com |
| expected-hostname | github.com |
| None | cb7fa109eca7d4156c889f474306b0e91336055e9adf8fd4684b61e49094d124 |
| 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 | 2b59d31a4e44f08b7af67a4b67f8fd0af3befe2a |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width