Title: Mapped type filtering - thoughts and discussion · Issue #17678 · microsoft/TypeScript · GitHub
Open Graph Title: Mapped type filtering - thoughts and discussion · Issue #17678 · microsoft/TypeScript
X Title: Mapped type filtering - thoughts and discussion · Issue #17678 · microsoft/TypeScript
Description: This was briefly a gist, but now it's here with bonus typo (one was actually spelling, but I can pretend) corrections and vanish renamed to delete. This arrogantly assumes the implementation of #17636 - declaration type overloading. Aim ...
Open Graph Description: This was briefly a gist, but now it's here with bonus typo (one was actually spelling, but I can pretend) corrections and vanish renamed to delete. This arrogantly assumes the implementation of #17...
X Description: This was briefly a gist, but now it's here with bonus typo (one was actually spelling, but I can pretend) corrections and vanish renamed to delete. This arrogantly assumes the implementation of...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/17678
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Mapped type filtering - thoughts and discussion","articleBody":"This was briefly a [gist](https://gist.github.com/TheOtherSamP/eb60ba29f0091fdd87926b3eeeaee392), but now it's here with bonus typo (one was actually spelling, but I can pretend) corrections and `vanish` renamed to `delete`.\r\n\r\nThis arrogantly assumes the implementation of [#17636](https://github.com/Microsoft/TypeScript/issues/17636) - declaration type overloading.\r\n\r\n## Aim of mapped-type filtering\r\nGiven some type `Foo`, construct a new type `Bar` with a subset of the members of `Foo`, where that subset is determined by a type predicate. Both the key and type of the member should be available to the predicate. Type predicates should have the full power of the type system.\r\n\r\nThis is analogous to `Array.prototype.filter`, where the index and item value are available to the predicate.\r\n\r\n### Examples that should be achievable\r\nNote that some of these may be achievable within the language today, albeit via round-about means. The aim is to have all of these achievable _nicely_.\r\n\r\n```ts\r\n// Example predicate, should be reusable\r\ntype IsWantedType\u003cT> = ...;\r\n\r\n// {foo: \"world\", bar(): void} -> {foo: \"world\"}\r\ntype NonFunctionMembers\u003cT> = ...;\r\n\r\n// {foo: \"world\", bar(): void} -> {bar(): void}\r\ntype FunctionMembers\u003cT> = ...;\r\n\r\n// {foo: string, fizz: object} -> {foo: string}\r\ntype PrimitivesOnly\u003cT> = ...;\r\n```\r\n\r\n## How to do it?\r\nIt seems there are two basic ways that filtering could be implemented within the context of mapped-types.\r\n\r\nA mapped-type looks something like this:\r\n\r\n```ts\r\ntype MappedType\u003cT> = {[K in keyof T ]: T[K]};\r\n// ^ ^\r\n// A B\r\n```\r\n\r\nWhere `A` and `B` strike me as the two obvious sites where a filtering syntax would fit. I'm calling these LHS and RHS filtering respectively.\r\n\r\n### LHS filtering\r\nAt first glance, this seems the obvious place to put the filter. An intuitive syntax for this may look something like:\r\n\r\n```ts\r\ntype FilteredType\u003cT> = {[K in keyof T if ...]: T[K]};\r\n```\r\n\r\nStructurally this makes a lot of sense, and the for-in-if flow is nice. What to put in place of the ... is an issue, though.\r\n\r\nWere a type declaration to be used here, some concept of meaningful return type would have to be introduced to type declarations.\r\n\r\n#### Pseudo-value type predicates\r\nImagine the following example:\r\n\r\n```ts\r\n// Using type declaration overloads, this maps T to the types true or false\r\n// Note that these are the TYPES true and false, NOT the values\r\ntype IsPrimitive\u003cT extends object> = false;\r\ntype IsPrimitive\u003cT> = true;\r\n\r\ntype PrimitivesOnly\u003cT> = {[K in keyof T if IsPrimitive\u003cT[K]>]: T[K]};\r\n```\r\n\r\nThis actually reads really nicely. The downside to this is that we now have the compiler assigning meaning to the `true` and `false` _types_. This brings them uncomfortably close to values, and is a strange direction to take the language.\r\n\r\nAnother similar option would be to use truthiness and falsiness concepts here, perhaps any type other than `never` could be true. This suffers from most of the same issues as just using `true` and `false`, though may lead to different (nicer?) predicate type declarations.\r\n\r\n#### Constraint-matching type predicates\r\nConstraint matching could be used for the predicate. An example predicate may be defined and used like so:\r\n\r\n```ts\r\ntype IsObject\u003cT extends object> = T;\r\n\r\ntype ObjectsOnly\u003cT> = {[K in keyof T if IsObject\u003cT[K]>]: T[K]};\r\n```\r\n\r\nThe readability of this is pretty good.\r\n\r\nHere the result of the predicate is irrelevant, the filtering is done according to whether or not `T[K]` satisfies the constraints of the predicate. This seems like a nice approach until you realise that this manner of defining predicates is significantly less powerful and expressive. You can specify as many cases as you like where it _does_ match, but there's currently no syntax to specify a special case that _doesn't_ match.\r\n\r\n```ts\r\n// The lack of primitive type in the language means we have to list these allowed cases exhaustively\r\ntype IsPrimitive\u003cT extends string | number | boolean | symbol> = T;\r\n\r\n// Well now we're stuck, as there's no way to define a particular case that fails to match\r\ntype IsNotNumber\u003cT> = ...;\r\n```\r\n\r\nOne potential solution to this is subtraction-types.\r\n\r\n```ts\r\n// Can subtraction-types like this provide the full power of the other methods?\r\ntype IsNotNumber\u003cT extends any - number> = T;\r\n```\r\n\r\nAnother solution may be to introduce a new type that I'll call `throw` for now. A type that resolves to `throw` would be considered a compile-error in most contexts, and would function the same as a constraint-match failure in a mapped-type.\r\n\r\n```ts\r\n// Compile-error\r\ntype Foo = throw;\r\n\r\n// This overloaded type would behave as if the second overload doesn't exist\r\ntype Foo\u003cT extends number> = number;\r\ntype Foo\u003cT> = throw;\r\n\r\n// This would be a working IsPrimitive\u003cT>\r\ntype IsPrimitive\u003cT extends object> = throw;\r\ntype InPrimitive\u003cT> = T;\r\n```\r\n\r\nThis `throw` approach is pretty weird, but compared to subtraction-types arguably leads to neater predicates.\r\n\r\n### RHS filtering\r\nFiltering in the RHS position initially makes a little less semantic/intuitive sense. One nice way to think about it may be that the type can be a normal type, or it can be nonexistant. \r\n\r\nFor this approach I'm proposing a new special type that I'm calling `delete` until I think of something better. `delete` describes a member that _does not exist_.\r\n\r\nThese two interfaces are _exactly_ identical. `OnlyHasFoo1` does not have a member `bar`, it would not show up in intellisense or `keyof` results or anywhere else. There is no ~spoon~`bar`.\r\n\r\n```ts\r\ninterface OnlyHasFoo1 {\r\n foo: number;\r\n bar: vanish;\r\n}\r\n\r\ninterface OnlyHasFoo2 {\r\n foo: number;\r\n}\r\n```\r\n\r\nThis would allow filters to be written as follows:\r\n\r\n```ts\r\n// Using type declaration overloads \r\ntype FilterPrimitivesOnly\u003cT extends object> = vanish;\r\ntype FilterPrimitivesOnly\u003cT> = T;\r\n\r\ntype PrimitivesOnly\u003cT> = {[K in keyof T]: FilterPrimitivesOnly\u003cT[K]>};\r\n```\r\nThis does not read as nicely as the LHS filter approach above, but in my opinion, this gels considerably better with the nature of the language as it currently exists. While `delete` is a fairly odd concept, it still describes the behaviour of the type, rather than being a pseudo-value as `true` and `false` become in the LHS approach above.\r\n\r\n`delete` may also find other uses. Perhaps declaration merging with `delete` could remove members? Or some complex type combinations would find a use for `delete`? That remains to be explored. \r\n\r\nThe specifics of `delete` would need to be pinned down, particularly how it combines with other types. `vanish | T` -> `delete`, `vanish & T` -> `T` is where I'm at with that now, though that's not based on much. Interactions between `delete` and `never` and `any` would have to be worked out.\r\n\r\nThis also poses the question of whether any non-existent member access should now have type `delete`, and what that may mean and what use it may have. Should `type Foo = {}[\"non-existent\"]` now be `delete`?\r\n\r\n## In summary / thoughts\r\n\r\nI think some version of the constraint-matching type predicates solution would probably be my pick, but all of these have their pros and cons, and none is the clear leader in my eyes. There may of course be other better options I haven't even considered.","author":{"url":"https://github.com/SamPruden","@type":"Person","name":"SamPruden"},"datePublished":"2017-08-08T05:36:09Z","url":"https://github.com/microsoft/TypeScript/issues/17678"}
| 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:d45cc375-b25f-d368-c200-3f47afdb12aa |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8678:1148D3:2DAB792:3A48E90:6B01C13A |
| html-safe-nonce | 73b0798b7814b3efa8c6db7433f9590971a82a710753d6ec53312496f9270011 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4Njc4OjExNDhEMzoyREFCNzkyOjNBNDhFOTA6NkIwMUMxM0EiLCJ2aXNpdG9yX2lkIjoiNDc0NDA3ODI0MTA5Mjk3Njk1NCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | f831b8f6c08f70540b93989767b27c42860ba5118cb730dd209b56fdb213a34f |
| hovercard-subject-tag | issue:248605618 |
| 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/17678/issue_layout |
| twitter:image | https://opengraph.githubassets.com/1bbff12f265ca95428ab30c9db8052deab97131ba8a01ac4511d075954770eb0/microsoft/TypeScript/issues/17678 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/1bbff12f265ca95428ab30c9db8052deab97131ba8a01ac4511d075954770eb0/microsoft/TypeScript/issues/17678 |
| og:image:alt | This was briefly a gist, but now it's here with bonus typo (one was actually spelling, but I can pretend) corrections and vanish renamed to delete. This arrogantly assumes the implementation of #17... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | SamPruden |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| 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 | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width