microsoft / microsoft/TypeScript
Suggestion: treat readonly static members of class as namespace members
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
static member; namespace; type
Maybe related issues: https://github.com/microsoft/TypeScript/issues/38207
Suggestion
Readonly static members of class should act like namespace members. Especially, when that member is assigned as an alias of enumeration or other class.
Use Cases
With the suggestion,
enum Color { red, }
class Image {
public static readonly Color = Color; // Marked as readonly, so tsc can ensure it's an alias
}
The Image.Color should be an alias of enumeration Color. So we can use it when an enumeration may be used:
console.log(Image.Color.red); // OK
function f(color: Image.Color) { // OK: used as type #1
if (color === Image.Color.red){ /* ... */ }
}
#1 is invalid for now because tsc does not treat Image.Color as a type.
To use Image.Color as a type, we may supply a verbose declaration according to the declaration merging rule of TypeScript:
namespace Image {
export type Color = (typeof Color)[keyof typeof Color]; // :(
}
It's verbose...
Examples
Sometimes we want to embed enumerations, classes into other classes. Because we don't want directly expose that enumueration/class into module scope.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's examples and the related issue #38207, then trace how TypeScript handles static readonly members, namespace members, and type positions. Done means an enum or class aliased through a readonly static member can be used both as a value and as a type without the verbose namespace declaration.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100