Title: Singleton types under the form of string literal types · Issue #1003 · microsoft/TypeScript · GitHub
Open Graph Title: Singleton types under the form of string literal types · Issue #1003 · microsoft/TypeScript
X Title: Singleton types under the form of string literal types · Issue #1003 · microsoft/TypeScript
Description: This proposal is based on a working prototype located at https://github.com/Nevor/TypeScript/tree/SingletonTypes String literal types extended to the whole language This change would bring singleton types created from literal string to c...
Open Graph Description: This proposal is based on a working prototype located at https://github.com/Nevor/TypeScript/tree/SingletonTypes String literal types extended to the whole language This change would bring singleto...
X Description: This proposal is based on a working prototype located at https://github.com/Nevor/TypeScript/tree/SingletonTypes String literal types extended to the whole language This change would bring singleto...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/1003
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Singleton types under the form of string literal types","articleBody":"This proposal is based on a working prototype located at https://github.com/Nevor/TypeScript/tree/SingletonTypes\n## String literal types extended to the whole language\n\nThis change would bring singleton types created from literal string to complete recent addition of type aliases and union types. This would hopefully satisfy those that mentioned string enum and tagged union in previous PRs (#805, #186).\n\nThis addition would be short thanks to a concept that was already implemented internally for \".d.ts\" files.\n## Use cases\n\nOften operational distinction of function and values are done with an companion finite set of string that are used as tags. For instance events handler types rely on strings like \"mouseover\" or \"mouseenter\". \n\nSometimes string are often themselves operating on a finite definite set of values that we want to convey this through specifications and have something to enforce it. \n\nAnd for more advanced typing, we sometimes use types themselves as informations to guide function usages, constraining a little further the base types.\n## Current workarounds\n\nThere is no way to create string enum for now, the workaround is to manipulate variables assigned once and for all. This does not protect from typos that will gladly propagate everywhere a string is used.\n\nWhen we want to implement tagged union types for symbolic computation, we must use some number enum coupled with subtyping and casting machinery, losing all type safety.\n\nIn general, advanced type constraint are done through classes and this put us further away from simple records that would have been used in javascript.\n## Overview examples\n\n``` typescript\ntype result = \"ok\" | \"fail\" | \"abort\";\n\n// \"string enum\"\nfunction compute(n : number) : result {\n if(...) {\n return \"ok\";\n } else if (...) {\n return \"fail\";\n } else {\n return \"crash\"; // Error, not accepted\n }\n}\n\nfunction checkSuccess(o : result) : void { ... }\n\nvar res : result = compute(42);\n\ncheckSuccess(res); // OK\ncheckSuccess(\"crash\"); // Error\n\nres = \"crash\"; // Error\n\nvar message = res; // OK, message infered as string\nvar verbose = \"Current status : \" + res; // OK\n\n\n// Specifications constrains\ninterface operationAction {\n name : string;\n id : number;\n status : result;\n}\n\n// Usable as and with regular types\nvar results : result[] = [compute(3), compute(27), \"ok\"]; // Ok\nresults = [\"crash\", \"unknown\"]; // Error\n\ntype error_level = \"warning\" | \"fatal\";\n\ninterface Foo\u003cT> {\n foo : T;\n}\ninterface Toto\u003cU> {\n value : Foo\u003cresult> | { unknown : string; value : U };\n}\n\nvar foo : Toto\u003cerror_level> = { foo : \"ok\" }; // OK\nvar foo : Toto\u003cerror_level> = { foo : \"crash\" }; // Error\nvar foo : Toto\u003cerror_level> = { unknown : \"Unknown error\", value : \"warning\" }; // OK\nvar foo : Toto\u003cerror_level> = { unknown : \"Unknown error\", value : \"trace\" }; // Error\n\n\n// Disjoint union\ntype obj = { kind : \"name\"; name : string } | { kind : \"id\"; id : number } | { kind : \"internal\" ; id : number }\n\nvar o : obj = { kind : \"name\", name : \"foo\", id : 3 } \nvar o : obj = { kind : \"id\", name : \"foo\", id : 3 } \n// Both object are strictly distinguished by their kind\n\nvar o : obj = { kind : \"unknown\", name : \"something\" }; // Error\n\ntype classical_obj : { name : string } | { id : number };\n\nvar c_o : classical_obj = { name : \"foo\", id : 3 }; // A supertype of both is assignable, we lose infos \n\n```\n## Typing specifications\n- any string literal as type \"s\" (StringLiteralType) where s is the content of the literal.\n- every StringLiteralTypes are subtypes of string, the reverse is not true.\n- two StringLiteralTypes are compatible if and only if they represent the same string literal.\n\n``` typescript\ntype ok = \"ok\"\n\n\nvar a : ok = \"ok\";\nvar b : \"ok\" = a; // OK\n\nvar a : ok = \"no\"; // Error\nvar c : string = a; // OK \nvar a : ok = c; // Error \n```\n## Pitfalls and remaining work\n### Backward compatibility\n\nThis prototype is backward compatible (accepts programs that were accepted before) but in one case : \n\n``` typescript\nfunction ... {\n if (...) { \n return \"foo\";\n } else {\n return \"bar\";\n }\n}\n```\n\nThe compiler will raise an Error saying that there is no common type between \"foo\" and \"bar\". This is because the compiler only accept one of the return type to be supertype and does not widen before.\nWe might add a special case for StringLiteralTypes and keep other types as is, or, do some widening and therefore accept empty records for conflicting records for instance.\n### Error messages\n\nIt might confuse users that their literal strings are mentioned as types when they are expecting to see \"string\" even though this difference as no incidence on normally rejected string.\nThe compiler might display StringLiteralTypes as \"string\" whenever the conflict is not involved between two StringLiteralTypes.\n## Extending type guards\n\nTo be fully usable to distinguish records by type tags, type guards should be extended to take into account this kind singleton types. One would expect the following to work : \n\n``` typescript\ntype obj = { kind : \"name\"; name : string } | { kind : \"id\" ; id : number };\nvar o : obj = ...;\nif (o.kind == \"name\") {\n /* o considered as left type */\n} else if(o.kind == \"id\") {\n /* o considered as right type */\n}\n```\n","author":{"url":"https://github.com/Nevor","@type":"Person","name":"Nevor"},"datePublished":"2014-10-30T16:21:54Z","url":"https://github.com/microsoft/TypeScript/issues/1003"}
| 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:f067deca-3d65-77e4-3166-7454508f99fe |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D776:3C0CB1:4CDA51:6725A7:6AFBF00D |
| html-safe-nonce | 6283ced4486a2eee93a88d30495c2b2e7226d37d394fc29417c04dedbda2b787 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENzc2OjNDMENCMTo0Q0RBNTE6NjcyNUE3OjZBRkJGMDBEIiwidmlzaXRvcl9pZCI6IjQ0NDQxOTQ5NTcyNDE4NzIzOTciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | a4222bf85a27704d26ebc3001b43a5d9a1c28b3c59fb61681df51fa5cc9cf5b8 |
| hovercard-subject-tag | issue:47291043 |
| 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/1003/issue_layout |
| twitter:image | https://opengraph.githubassets.com/c77685687a0190370684a3dbb945069b570bb8c7a77acb2476cc1cd75776c676/microsoft/TypeScript/issues/1003 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/c77685687a0190370684a3dbb945069b570bb8c7a77acb2476cc1cd75776c676/microsoft/TypeScript/issues/1003 |
| og:image:alt | This proposal is based on a working prototype located at https://github.com/Nevor/TypeScript/tree/SingletonTypes String literal types extended to the whole language This change would bring singleto... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Nevor |
| hostname | github.com |
| expected-hostname | github.com |
| None | fa74413a1d84dac536fcca0740780bcbd3207bafec0e51873b73ff8e8cca032f |
| 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 | b3b5633a74535d9c23385512d534c66c8fde1907 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width