-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type-mutating functions #27568
Comments
Also #10421. |
Effectively the same as #10421 |
This seems like a nice feature to have that can model a lot of old "mixin" style code that was/is used in JS code. Even for more modern code it would be useful (like mentioned assert functions). I personally had situation when I was migrating old code to TS and this feature would allow me to just annotate function that modified type of passed object. I had to change the function and caller code to use new object returned by this function. It wasn't a big issue in this case but slowed down a bit migration to TS. @RyanCavanaugh Can you tell a bit more why it was rejected in Suggestion Backlog Slog? Your comment "No control flow nodes to attach this to" doesn't tell me much 🙁 Does it mean "Not easy to implement and this feature doesn't seem that valuable"? 😜 |
We think it's very valuable, but have no ideas on how to implement it without completely blowing up performance |
Search Terms
Type guard, assert, decorator
Suggestion
Current type guard support syntax:
Consider following function:
This function changes a type of t to something else by adding a property, but it is not possible to tell to the TypeScript compiler that it does so. I propose that a new syntax is added:
After that the compiler would know that the the parameter given to the function hasd been mutated from one type to another. This would obviously work only for objects. After the change this would work:
Type guard can used for similar behavior. But the return statement in makeCube and the if statement feels unneeded.
Use Cases
This functionality could be used for implementing asserts, e.g. Assert.isNotNull which would make unit test environments easier if strict null checks are used. If you have a type T|null, then that could be mutated to T.
E.g.
Another use case is decorator pattern. The decorator could add more properties to an object and hence change the type of it.
Examples
See suggestion section.
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: