-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Support type-safe dictionaries where set of keys is finite #42477
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
This would be covered by #26797. |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
This was marked as duplicate of #26797, which was instead superseded by #44512, released in TypeScript 4.4. But this original issue remains unsolved in TypeScript 4.4. There is no indication that accessing attributes of Please re-open. Or redirect to another similar issue. |
Update: This behavior can be requested with Doc: https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess |
Inspiration is from this article https://levelup.gitconnected.com/building-type-safe-dictionaries-in-typescript-a072d750cbdf as well as practical problem that we encountered in our codebase.
If we want a type-safe dictionary where key is e.g. string we can simply use a
Record
:However, if we want to restrict set of keys:
Then suddenly TypeScript requires all keys to be present:
The only solution seems to be to allow
undefined
values withPartial
:However, this now breaks
Object.values
and in general it's not good because the type of value becomesnumber | undefined
, which is not what we want.Another issue is with
Object.entries
andObject.keys
which are not type-safe either.Suggestion
Support first-class type-safe dictionaries where set of keys is finite:
and provide type-safe
Object.keys
,Object.values
andObject.entries
.Dict
says that:K
.V
.Note that this is only about type-safety,
Dict
is still a plain JavaScript object.The text was updated successfully, but these errors were encountered: