Title: Spec Preview: Union types · Issue #805 · microsoft/TypeScript · GitHub
Open Graph Title: Spec Preview: Union types · Issue #805 · microsoft/TypeScript
X Title: Spec Preview: Union types · Issue #805 · microsoft/TypeScript
Description: Updated 10/3 (see comment for changelog) | operator for types This is a "spec preview" for a feature we're referring to as "union types". Anders Hejlsberg (@ahejlsberg) thought this up; I am merely providing the summary 😄 Use Cases Many ...
Open Graph Description: Updated 10/3 (see comment for changelog) | operator for types This is a "spec preview" for a feature we're referring to as "union types". Anders Hejlsberg (@ahejlsberg) thought this up; I am merely...
X Description: Updated 10/3 (see comment for changelog) | operator for types This is a "spec preview" for a feature we're referring to as "union types". Anders Hejlsberg (@ahejlsberg) thou...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/805
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Spec Preview: Union types","articleBody":"Updated 10/3 (see comment for changelog)\n## `|` operator for types\n\nThis is a \"spec preview\" for a feature we're referring to as \"union types\". @ahejlsberg thought this up; I am merely providing the summary :smile:\n### Use Cases\n\nMany JavaScript libraries support taking in values of more than one type. For example, jQuery's AJAX settings object's `jsonp` property can either be `false` or a `string`. TypeScript definition files have to represent this property as type `any`, losing type safety.\n\nSimilarly, Angular's http service configuration (https://docs.angularjs.org/api/ng/service/$http#usage) has properties that of \"either\" types such as \"`boolean` or `Cache`\", or \"`number` or `Promise`\".\n### Current Workarounds\n\nThis shortcoming can often be worked around in function overloads, but there is no equivalent for object properties, type constraints, or other type positions.\n## Introduction\n### Syntax\n\nThe new `|` operator, when used to separate two types, produces a _union type_ representing a value which is of _one_ of the input types.\n\nExample:\n\n``` ts\ninterface Settings {\n foo: number|string;\n}\nfunction setSetting(s: Settings) { /* ... */ }\nsetSettings({ foo: 42 }); // OK\nsetSettings({ foo: '100' }); // OK\nsetSettings({ foo: false }); // Error, false is not assignable to number|string\n```\n\nMultiple types can be combined this way:\n\n``` ts\nfunction process(n: string|HTMLElement|JQuery) { /* ... */ }\nprocess('foo'); // OK\nprocess($('div')); // OK\nprocess(42); // Error\n```\n\nAny type is a valid operand to the `|` operator. Some examples and how they would be parsed:\n\n``` ts\nvar x: number|string[]; // x is a number or a string[]\nvar y: number[]|string[]; // y is a number[] or a string[]\nvar z: Array\u003cnumber|string>; // z is an array of number|string\nvar t: F|typeof G|H; // t is an F, typeof G, or H\nvar u: () => string|number; // u is a function that returns a string|number\nvar v: { (): string; }|number; // v is a function that returns a string, or a number\n```\n\nNote that parentheses are not needed to disambiguate, so they are not supported.\n### Interpretation\n\nThe meaning of `A|B` is a type that is _either_ an `A` or a `B`. Notably, this is\ndifferent from a type that combines _all_ the members of `A` and `B`. We'll explore\nthis more in samples later on.\n## Semantics\n### Basics\n\nSome simple rules:\n- Identity: `A|A` is equivalent to `A`\n- Commutativity: `A|B` is equivalent to `B|A`\n- Associativity: `(A|B)|C` is equivalent to `A|(B|C)`\n- Subtype collapsing: `A|B` is equivalent to `A` if `B` is a subtype of `A`\n### Properties\n\nThe type `A|B` has a property `P` of type `X|Y` if `A` has a property `P` of type `X` and `B` has a property `P` of type `Y`. These properties must either both be public, or must come from the same declaration site (as specified in the rules for `private`/`protected`). If either property is optional, the resulting property is also optional.\n\nExample:\n\n``` ts\ninterface Car {\n weight: number;\n gears: number;\n type: string;\n}\ninterface Bicycle {\n weight: number;\n gears: boolean;\n size: string;\n}\nvar transport: Car|Bicycle = /* ... */;\nvar w: number = transport.weight; // OK\nvar g = transport.gears; // OK, g is of type number|boolean\n\nconsole.log(transport.type); // Error, transport does not have 'type' property\nconsole.log((\u003cCar>transport).type); // OK\n```\n### Call and Construct Signatures\n\nThe type `A|B` has a call signature `F` if `A` has a call signature\n`F` and `B` has a call signature `F`.\n\nExample:\n\n``` ts\nvar t: string|boolean = /* ... */;\nconsole.log(t.toString()); // OK (both string and boolean have a toString method)\n```\n\nThe same rule is applied to construct signatures.\n### Index Signatures\n\nThe type `A|B` has an index signature `[x: number]: T` or `[x: string]: T` if both `A` and `B` have an index signature with that type.\n### Assignability and Subtyping\n\nHere we describe assignability; subtyping is the same except that \"is assignable to\" is replaced with \"is a subtype of\".\n\nThe type `S` is assignable to the type `T1|T2` if `S` is assignable to `T1` or if `S` is assignable to `T2`.\n\nExample:\n\n``` ts\nvar x: string|number;\nx = 'hello'; // OK, can assign a string to string|number\nx = 42; // OK\nx = { }; // Error, { } is not assignable to string or assignable to number\n```\n\nThe type `S1|S2` is assignable to the type `T` if both `S1` and `S2` are assignable to `T`.\n\nExample:\n\n``` ts\nvar x: string|number = /* ... */;\nvar y: string = x; // Error, number is not assignable to string\nvar z: number = x; // Error, string is not assignable to number\n```\n\nCombining the rules, the type `S1|S2` is assignable to the type `T1|T2` if `S1` is assignable to `T1` or `T2` _and_ `S2` is assignable to `T1` or `T2`. More generally, every type on the right hand side of the assignment must be assignable to at least one type on the left.\n\nExample:\n\n``` ts\nvar x: string|number;\nvar y: string|number|boolean;\nx = y; // Error, boolean is not assignable to string or number\ny = x; // OK (both string and number are assignable to string|number)\n```\n## Best Common Type\n\nThe current Best Common Type algorithm (spec section 3.10) is only capable of producing a type that was among the candidates, or `{}`. For example, the array `[1, 2, \"hello\"]` is of type `{}[]`. With the ability to represent union types, we can change the Best Common Type algorithm to produce a union type when presented with a set of candidates with no supertype.\n\nExample:\n\n``` ts\nclass Animal { run(); }\nclass Dog extends Animal { woof(); }\nclass Cat extends Animal { meow(); }\nclass Rhino extends Animal { charge(); }\nvar x = [new Dog(), new Cat()];\n// Current behavior: x is of type {}[]\n// Proposed: x is of type Array\u003cDog|Cat>\n```\n\nNote that in this case, the type `Dog|Cat` is structurally equivalent to `Animal` in terms of its members, but it would still be an error to try to assign a `Rhino` to `x[0]` because `Rhino` is not assignable to `Cat` or `Dog`.\n\nBest Common Type is used for several inferences in the language. In the cases of `x || y`, `z ? x : y`, and `[x, y]`, the resulting type will be `X | Y` (where `X` is the type of `x` and `Y` is the type of `y`). For function return statements and generic type inference, we will require that a supertype exist among the candidates.\n\nExample\n\n``` ts\n// Error, no best common type among 'string' and 'number'\nfunction fn() {\n if(Math.random() > 0.5) {\n return 'hello';\n } else { \n return 42;\n }\n}\n// OK with type annotation\nfunction fn(): string|number {\n /* ... same as above ... */\n}\n```\n## Possible Next Steps\n### Combining Types' Members\n\nOther scenarios require a type constructed from `A` and `B` that has all members present in _either_ type, rather than in both. Instead of adding new type syntax, we can represent this easily by removing the restriction that `extends` clauses may not reference their declaration's type parameters.\n\nExample:\n\n``` ts\ninterface HasFoo\u003cT> extends T {\n foo: string;\n}\ninterface Point {\n x: number;\n y: number;\n}\nvar p: HasFoo\u003cPoint> = /* ... */;\nconsole.log(p.foo); // OK\nconsole.log(p.x.toString(); // OK\n```\n### Local Meanings of Union Types\n\nFor union types where an operand is a primitive, we could detect certain syntactic patterns and adjust the type of an identifier in conditional blocks.\n\nExample:\n\n``` ts\nvar p: string|Point = /* ... */;\nif(typeof p === 'string') {\n console.log(p); // OK, 'p' has type string in this block\n} else {\n console.log(p.x.toString()); // OK, 'p' has type Point in this block\n}\n```\n\nThis might also extend to membership checks:\n\n``` ts\ninterface Animal { run(); }\ninterface Dog extends Animal { woof(); }\ninterface Cat extends Animal { meow(); }\nvar x: Cat|Dog = /* ... */;\nif(x.woof) {\n // x is 'Dog' here\n}\nif(typeof x.meow !== 'undefined') {\n // x is 'Cat' here\n}\n```\n","author":{"url":"https://github.com/RyanCavanaugh","@type":"Person","name":"RyanCavanaugh"},"datePublished":"2014-10-02T02:34:19Z","url":"https://github.com/microsoft/TypeScript/issues/805"}
| 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:7ddecd23-fbf8-8cb3-3303-4912004255a2 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 85EA:31263D:40A143:56A00A:6AFBEC6B |
| html-safe-nonce | 99f8dd82f89ca0eba9c84b68ce5e928235ac2b3d601c17e780e526554c5a223c |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4NUVBOjMxMjYzRDo0MEExNDM6NTZBMDBBOjZBRkJFQzZCIiwidmlzaXRvcl9pZCI6IjIyMTAzNjU0MzI3NTE5NzU1MzEiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | e891ca245a135872358973cc394b6c658244ca594ff5fa75992d3ae75fcbe930 |
| hovercard-subject-tag | issue:44641008 |
| 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/805/issue_layout |
| twitter:image | https://opengraph.githubassets.com/5c73a2dfe845bc4f402247ca21cc3a4eeb3090145ce5183e77927324d5357811/microsoft/TypeScript/issues/805 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/5c73a2dfe845bc4f402247ca21cc3a4eeb3090145ce5183e77927324d5357811/microsoft/TypeScript/issues/805 |
| og:image:alt | Updated 10/3 (see comment for changelog) | operator for types This is a "spec preview" for a feature we're referring to as "union types". Anders Hejlsberg (@ahejlsberg) thought this up; I am merely... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | RyanCavanaugh |
| hostname | github.com |
| expected-hostname | github.com |
| None | 744d4381b1c4dbd6d8736c7d7e5bbe7dc11217584e457a3555020c631764e8ec |
| 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 | df859c48a4c8b4c0009c19bb4e82101aacb4b998 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width