You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 Record<> may return undefined for nonexistant keys. And there is no Dict<> type as proposed in this issue.
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: