Title: Type predicate expressions and 'this' type assertions · Issue #12942 · microsoft/TypeScript · GitHub
Open Graph Title: Type predicate expressions and 'this' type assertions · Issue #12942 · microsoft/TypeScript
X Title: Type predicate expressions and 'this' type assertions · Issue #12942 · microsoft/TypeScript
Description: The type system currently allows to specify basic type constraints (or 'assertions') on polymorphic types, for example: function example
Open Graph Description: The type system currently allows to specify basic type constraints (or 'assertions') on polymorphic types, for example: function example
X Description: The type system currently allows to specify basic type constraints (or 'assertions') on polymorphic types, for example: function example<T extends Array<any>>(a: T) {}; However,...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/12942
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Type predicate expressions and 'this' type assertions","articleBody":"The type system currently allows to specify basic type constraints (or 'assertions') on polymorphic types, for example:\r\n\r\n```ts\r\nfunction example\u003cT extends Array\u003cany>>(a: T) {};\r\n```\r\n\r\nHowever, currently there is no elegant syntax for types to declare constraints on _themselves_. Here's a real world example where I needed something like this:\r\n\r\nI have a class containing several methods:\r\n\r\n```ts\r\nclass MyClass {\r\n\tread(filename: string, byteCount: number): string {\r\n\t\t// ...\r\n\t}\r\n\r\n\twrite(filename: string, text: string): void {\r\n\t\t// ...\r\n\t}\r\n\r\n\tdelete(filename: string): void {\r\n\t\t// ...\r\n\t}\r\n}\r\n```\r\n\r\nand I want to write a known (i.e. monomorphic) type that is constrained to exactly match the _keys_ of `MyClass` (the property types don't matter for this example, so I annotated them with ` { ... }`, for simplicity, also note that `MyType` is intended to be user-customizable and cannot be deterministically generated using a mapped type):\r\n\r\n```ts\r\ntype MyType = {\r\n\tread: { ... };\r\n\twrite: { ... };\r\n\tdelete: { ... };\r\n}\r\n```\r\n\r\nThe best hack/workaround I found so far was to declare additional dummy types, that would fail if `MyType` doesn't satisfy the expected constraint:\r\n\r\n```ts\r\ntype Extends\u003cT1 extends T2, T2> = boolean; // The 'boolean' doesn't really have any meaning here.\r\n\t\t\t\t\t// It can technically be any type.\r\n\t\t\t\t\t// I only used it because I needed to fill out some sort of\r\n\t\t\t\t\t// type association to satisfy the compiler.\r\n\r\n// These types are never actually used. They are only here to force the program not to type-check \r\n// if their supplied arguments don't satisfy the constraints for the Extends\u003c..> type parameters:\r\ntype DummyAssertionType1 = Extends\u003ckeyof MyType, keyof MyClass>;\r\ntype DummyAssertionType2 = Extends\u003ckeyof MyClass, keyof MyType>;\r\n```\r\n\r\nThe hack does seems to work so far, and has proven useful in practice, so by itself that's a significant improvement over having nothing at all. However, it is not very elegant or readable and violates type 'encapsulation'. It would be cool if I could instead write something like:\r\n\r\n```ts\r\ntype SameKeys\u003cT1, T2> = (keyof T1 extends keyof T2) && (keyof T2 extends keyof T1);\r\n\r\ntype MyType where SameKeys\u003cthis, MyClass> = {\r\n\tread: { ... };\r\n\twrite: { ... };\r\n\tdelete: { ... };\r\n}\r\n```\r\n\r\nI'll try to break down what is happening here:\r\n\r\n* The `SameKeys` type contains a type expression that evaluates to either the `true` or `false` boolean literal types. Given `P1`, `P2` are valid type predicate expressions (e.g. `T extends U`) then `P1 && P2`, `P1 || P2` `!P1` are also type predicate expressions etc.\r\n* The `where` keyword simply implies that the following type or type expression must evaluate to a boolean literal type and in particular to `true` for the constrained type to be valid.\r\n\r\n_[Edit: removed some confusing examples, see the next comment]_\r\n\r\nThe concept can also be used with interfaces, or even classes:\r\n\r\n```ts\r\ninterface MyInterface\u003cT, U> where SomeComplexPredicate\u003cthis, T, U> { \r\n // ...\r\n}\r\n\r\nclass MyClass\u003cT, U> where SomeComplexPredicate\u003cthis, T, U> { \r\n //...\r\n}\r\n```\r\n\r\n_Edit: changed the suggested `satisfies` keyword to `where` as I believe it gives slightly better readability._","author":{"url":"https://github.com/rotemdan","@type":"Person","name":"rotemdan"},"datePublished":"2016-12-15T11:26:49Z","url":"https://github.com/microsoft/TypeScript/issues/12942"}
| 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:ff44af55-4393-5a37-44b1-fbdf2120b7db |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D834:38C5CF:96D18A:C424E2:6B00DE0D |
| html-safe-nonce | 4184066d88ef0cf305924b795f5f14bb2a0e321f47b412a878e9899ca5cc3837 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEODM0OjM4QzVDRjo5NkQxOEE6QzQyNEUyOjZCMDBERTBEIiwidmlzaXRvcl9pZCI6IjQwNTk1MTQ4NjcwNTExOTE4MjEiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | eb3c7f9ad83ac75b5257c4cbdabcf2654146a3be04a12e96e9b4107e2c505282 |
| hovercard-subject-tag | issue:195781654 |
| 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/12942/issue_layout |
| twitter:image | https://opengraph.githubassets.com/de954bfe3e961597f2c1686dd237a95fd1e2ad0fa389c6a3aa639a9211756d83/microsoft/TypeScript/issues/12942 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/de954bfe3e961597f2c1686dd237a95fd1e2ad0fa389c6a3aa639a9211756d83/microsoft/TypeScript/issues/12942 |
| og:image:alt | The type system currently allows to specify basic type constraints (or 'assertions') on polymorphic types, for example: function example |
| 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 | 043c3f30fbcbe2c6c8e729e10cbbbc90c406546f9fbbb67c648d38f6b7d16daf |
| 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 | 5425dc24e8bd8d6fca9641a12afc984825a43875 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width