Title: Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type · Issue #36348 · microsoft/TypeScript · GitHub
Open Graph Title: Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type · Issue #36348 · microsoft/TypeScript
X Title: Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type · Issue #36348 · microsoft/TypeScript
Description: Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type What? In TypeScript, when a class is created and bound to a name via a class declaration, the name can be used in both val...
Open Graph Description: Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type What? In TypeScript, when a class is created and bound to a name via a class decla...
X Description: Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type What? In TypeScript, when a class is created and bound to a name via a class d...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/36348
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type","articleBody":"# Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type\r\n\r\n## What?\r\n\r\nIn TypeScript, when a class is created and bound to a name via a class declaration, the name can be used in both value and type positions. In contrast, when a class is bound to a name via `const`, `let`, or `var`, the name can only be used in value positions.\r\n\r\nI propose that when a class is bound to a name via `const`, `let`, or `var`, the name should be usable in both value and type positions, and that when such a name is used in a type position, it be interpreted as the instance type of the bound class value.\r\n\r\nMore formally:\r\n\r\n- A name should be deemed a _ClassValueName_ if:\r\n - It is declared via a `const`, `let`, or `var` statement, and\r\n - Its type is assignable to `new (...args: any[]) => any`, and\r\n - Its type is not `any`\r\n- A _ClassValueName_ should be usable in any type position that a class declaration name could be used in, and\r\n- A _ClassValueName_ used in a type position should be interpreted as the instance type of the class value, in the same way that a class declaration name used in a type position is interpreted as the instance type of the class declaration\r\n\r\n### Examples of proposed behaviour\r\n\r\n```typescript\r\n// `Foo` is of type `new () => {}`\r\nconst Foo = class {};\r\n\r\n// `Foo` can be used in a type position here, and `foo` is of type `{}`\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n```typescript\r\n// `Foo` is of type `new \u003cT>(value: T) => { value: T }`\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n\r\n// `Foo` can be used in a type position here (and is generic), and `foo` is of type `{ value: number }`\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\n```typescript\r\nfunction newFooClass() {\r\n return class \u003cT> { constructor(public value: T) {} };\r\n}\r\n\r\n// `Foo` is of type `new \u003cT>(value: T) => { value: T }`\r\nconst Foo = newFooClass();\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\n```typescript\r\nconst classes = {\r\n Foo: class \u003cT> { constructor(public value: T) {} }\r\n};\r\n\r\n// `Foo` is of type `new \u003cT>(value: T) => { value: T }`\r\nconst { Foo } = classes;\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\n```typescript\r\nconst withBrand =\r\n \u003cB extends string>(brand: B) =>\r\n \u003cC extends new (...args: any[]) => {}>(ctor: C) =>\r\n class extends ctor {\r\n brand: B = brand;\r\n };\r\n\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n// `FooWithBrand` is of type `new \u003cT>(value: T) => ({ value: T } & { brand: 'Foo' })`\r\nconst FooWithBrand = withBrand('Foo')(Foo);\r\n\r\n// `FooWithBrand` can be used in a type position here (and is generic), and `fooWithBrand` is of type `{ value: number } & { brand: 'Foo' }`\r\nconst fooWithBrand: FooWithBrand\u003cnumber> = new FooWithBrand(42);\r\n```\r\n\r\n## Why?\r\n\r\n### Unlike a class declaration, a class value requires a separate type declaration to expose the class's instance type\r\n\r\nFor class declarations, we can simply use the name of the class in a type position to reference its instance type:\r\n\r\n```typescript\r\nclass Foo {}\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\nBut for class values, a separate type declaration is required:\r\n\r\n```typescript\r\nconst Foo = class {};\r\n\r\ntype Foo = InstanceType\u003ctypeof Foo>;\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\nRequiring a separate type declaration has a few issues:\r\n\r\n- It's inconsistent with class declarations (which don't require a manual type declaration)\r\n- It doesn't work for generic classes (see next section)\r\n- It's boilerplate (which adds up, especially with multiple classes in the same file)\r\n\r\nWith this proposal however, we wouldn't need a separate type declaration, and all of the following would just work:\r\n\r\n```typescript\r\nconst Foo = class {};\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n```typescript\r\nfunction newFooClass() { return class {}; }\r\n\r\nconst Foo = newFooClass();\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n```typescript\r\nconst classes = { Foo: class {} };\r\n\r\nconst { Foo } = classes;\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n### There is currently no way to access the generic instance type of a generic class value\r\n\r\nNone of the following work:\r\n\r\n```typescript\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n// => Error: 'Foo' refers to a value, but is being used as a type here.\r\n```\r\n\r\n```typescript\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n\r\ntype Foo = InstanceType\u003ctypeof Foo>;\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n// => Error: Type 'Foo' is not generic.\r\n```\r\n\r\n```typescript\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n\r\ntype Foo\u003cT> = InstanceType\u003ctypeof Foo\u003cT>>;\r\n// => Error: '>' expected.\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\n```typescript\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n\r\ntype Foo\u003cT> = InstanceType\u003ctypeof Foo>\u003cT>;\r\n// => Error: ';' expected.\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\nWith this proposal however, we could simply use the name of the class value in a type position to reference its generic instance type:\r\n\r\n```typescript\r\nconst Foo = class \u003cT> { constructor(public value: T) {} };\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n// => No error\r\n```\r\n\r\n### It enables a potential workaround for [#4881](https://github.com/microsoft/TypeScript/issues/4881)\r\n\r\nThis doesn't work:\r\n\r\n```typescript\r\nconst withBrand =\r\n \u003cB extends string>(brand: B) =>\r\n \u003cC extends new (...args: any[]) => {}>(ctor: C) =>\r\n class extends ctor {\r\n brand: B = brand;\r\n };\r\n\r\n@withBrand('Foo')\r\nclass FooWithBrand\u003cT> {\r\n constructor(readonly value: T) {}\r\n}\r\n\r\ntype FooBrand\u003cT> = FooWithBrand\u003cT>['brand'];\r\n// => Error: Property 'brand' does not exist on type 'FooWithBrand\u003cT>'.\r\n```\r\n\r\nBut with this proposal, we could do this:\r\n\r\n```typescript\r\nconst withBrand =\r\n \u003cB extends string>(brand: B) =>\r\n \u003cC extends new (...args: any[]) => {}>(ctor: C) =>\r\n class extends ctor {\r\n brand: B = brand;\r\n };\r\n\r\nconst FooWithBrand = withBrand('Foo')(\r\n class \u003cT> {\r\n constructor(public value: T) {}\r\n }\r\n);\r\n\r\ntype FooBrand\u003cT> = FooWithBrand\u003cT>['brand'];\r\n```\r\n\r\nWhile this wouldn't be type support for actual decorators, it would at least provide _a_ means of class decoration that's reflected at the type level.\r\n\r\n### Flow supports this (there is prior art)\r\n\r\nThe following all work in Flow:\r\n\r\n```typescript\r\nconst Foo = class {};\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n```typescript\r\nconst Foo = class \u003cT> {\r\n value: T;\r\n constructor(value: T) { this.value = value; }\r\n};\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(12);\r\n```\r\n\r\n```typescript\r\nfunction newFooClass() { return class {}; }\r\n\r\nconst Foo = newFooClass();\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n```typescript\r\nfunction newFooClass() {\r\n return class \u003cT> {\r\n value: T;\r\n constructor(value: T) { this.value = value; }\r\n };\r\n}\r\n\r\nconst Foo = newFooClass();\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\n```typescript\r\nconst classes = { Foo: class {} };\r\n\r\nconst { Foo } = classes;\r\n\r\nconst foo: Foo = new Foo();\r\n```\r\n\r\n```typescript\r\nconst classes = {\r\n Foo: class \u003cT> {\r\n value: T;\r\n constructor(value: T) { this.value = value; }\r\n }\r\n};\r\n\r\nconst { Foo } = classes;\r\n\r\nconst foo: Foo\u003cnumber> = new Foo(42);\r\n```\r\n\r\nWhile feature parity with Flow is obviously not one of TypeScript's goals, Flow supporting this behaviour means that there's at least a precedent for it.\r\n\r\n## Why not?\r\n\r\n### It _may_ be a breaking change\r\n\r\nDepending on the implementation approach, this may be a breaking change.\r\n\r\nFor example, if this proposal were to be implemented by having the compiler automagically generate a separate type name whenever it encountered a _ClassValueName_, the generated type name may clash with an existing type name and break that currently working code.\r\n\r\nOn the other hand, if it were possible to implement this proposal using some kind of fallback mechanism (such as preferring any existing type name over using a _ClassValueName_ in a type position, for instance), then the change would be backwards compatible.\r\n\r\nIt is currently unclear whether or not the proposed change can be implemented in a backwards compatible manner.\r\n\r\n### It \"muddies\" the separation between the value and type namespaces\r\n\r\nTypeScript maintains separate namespaces for values and types. While this separation is fairly core to the language, there are already several exceptions in the form of class declarations, enums, and namespaces.\r\n\r\nThis proposal would introduce a new exception to that separation. This exception is particularly notable, as it would mark the first time a `const`, `let`, or `var`-declared name would be permitted in a type position. This is in contrast to all current exceptions, which each have construct-specific declaration syntax that differentiates them from standard variable declarations.\r\n\r\nThis proposal's \"muddying\" of the separation between the value and type namespaces may be confusing and/or surprising for both new and existing TypeScript users.\r\n\r\n## Next steps\r\n\r\n- [ ] Get feedback from both the TypeScript team and the community\r\n- [ ] Investigate potential implementation strategies\r\n\r\n## Checklist\r\n\r\nMy suggestion meets these guidelines:\r\n\r\n* [ ] This wouldn't be a breaking change in existing TypeScript/JavaScript code (**unclear at this stage**)\r\n* [x] This wouldn't change the runtime behavior of existing JavaScript code\r\n* [x] This could be implemented without emitting different JS based on the types of the expressions\r\n* [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)\r\n* [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).\r\n","author":{"url":"https://github.com/treybrisbane","@type":"Person","name":"treybrisbane"},"datePublished":"2020-01-22T09:23:25Z","url":"https://github.com/microsoft/TypeScript/issues/36348"}
| 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:fd574218-66cd-836a-a8c8-7064c8bb57a9 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BA46:882E2:93947D:C519D3:6B00E112 |
| html-safe-nonce | 30eda73d0bda5b859d07279994d1288275140655503632d41a22d9233fa1a1ae |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQTQ2Ojg4MkUyOjkzOTQ3RDpDNTE5RDM6NkIwMEUxMTIiLCJ2aXNpdG9yX2lkIjoiMTkzOTI2MTQ2MjAzMTY4Nzk1NCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | ecf4bd4dcd3e9037695d29eda07f121acab300d3501810795f7cfb21068731df |
| hovercard-subject-tag | issue:553410230 |
| 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/36348/issue_layout |
| twitter:image | https://opengraph.githubassets.com/adf975d418180aafce3c2aac6549f70e80ea7c4462946f142ac098cf097784c9/microsoft/TypeScript/issues/36348 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/adf975d418180aafce3c2aac6549f70e80ea7c4462946f142ac098cf097784c9/microsoft/TypeScript/issues/36348 |
| og:image:alt | Proposal: Allow a name bound to a class value to be used in a type position to reference the class's instance type What? In TypeScript, when a class is created and bound to a name via a class decla... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | treybrisbane |
| hostname | github.com |
| expected-hostname | github.com |
| None | 27088b6977484d0d3321d9a11c907c6d6637b315cfa359ef7952dbf6292f9b14 |
| 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 | 624179fb8b88d26ba5bba08894eb60a1c5a1d93d |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width