-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Make object type const with a keyword #61681
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
Comments
|
Duplicate #12936 |
Sounds similar to Exact Types. The problem is if you don't have comprehensive exact types support, there is no shortage of ways of accidentally extending your non-extensible object. type MyArgumentObj = { foo: 10, bar: 20 } is const;
function callThing(input: MyArgumentObj ) {
}
function mutator(victim: {foo: number, bar: number, baz?: number}) {
victim.baz = 0xdeadbeef;
}
const myObj = {
foo: 10 as const,
bar: 20 as const,
};
mutator(myObj); // uh-oh
callThing(myObj); |
@RyanCavanaugh Yes it seems this is what I request here. Pretty shame that this feature request is hanging since 2016. |
Uh oh!
There was an error while loading. Please reload this page.
🔍 Search Terms
The idea came from this Twitter discussion:
https://x.com/Cal_Irvine/status/1920844023507325084
about this code:
and why
keys
is of typestring[]
I understand that obj can be extended, like in this example:
This is more of a question that only designers of the language can answer. So this is not something for StackOverflow and I don't see any other place with discussions.
Why not adding a keyword that make the type
input: MyArgumentObj
only accept object with the same shape and make sure that it's properly type checked in the whole codebase and not extendedSomething like:
That will be a type error. If this was implemented,
Object.keys()
could return('foo' | 'bar')[]
as a lot people would expect and complain about. And thisconst
type could be added to this object as well:And every code that mutate the object with this type should throw type error.
I'm not sure if this is doable or what are the limitations, so this is more of a question why it's not possible?
Of course the syntax can be different.
✅ Viability Checklist
⭐ Suggestion
See above
📃 Motivating Example
See above
💻 Use Cases
See above
The text was updated successfully, but these errors were encountered: