WIP: Custom eslint rule to catch unsafe Record<string, T> #147
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
See https://dev.to/sarioglu/avoiding-unintended-undefined-values-while-using-typescript-record-4igo for general explanation.
Specific Context That Led Here:
Hotfix https://github.com/dsernst/siv/commit/921b308da3c7560f6c0fde99531848d0b9753d69 was needed earlier today to fix a broken results page. Typescript could have warned about the fatal error but didn't because of the unsafe
ballot_items_by_id: Record<string, Item>typing, which implies all string indices are defined.Thus the front end crashed by trying to access
undefined.type.Itemdoes always has a.type, but the index was sometimes wrong, resulting in valueundefinednotItem.Warning about type danger
The idea beginning to emerge here is to have a custom eslint rule that warns about directly referencing
Record<string, SomeType>.Better alternatives:
Partial<Record<string, SomeType>>if you really don't know the indices. Eg user supplied data such as ballot columns.type SafeRecord<SomeType> = Partial<Record<string, SomeType>>, shorthand for the above.Record<string, SomeType | undefined>another way to write the same thingRecord<ExplicitListOfKeys, SomeType>when you do know the keys ahead of time.Status — 100+ other potential cases?
The eslint rule is written and seems to be working now. Example:
Pushing up this Work-in-Progress on it for now, although it might be a bit to really go through the 108 cases it already identified, fix their typing, and see if this is really the best solution.