fp-ts icon indicating copy to clipboard operation
fp-ts copied to clipboard

Make JsonRecord type safe

Open thewilkybarkid opened this issue 3 years ago • 4 comments

The JsonRecord type currently allows you to access any string key, but this isn't type safe. Looking at the commit history the type came from https://github.com/Microsoft/TypeScript/issues/1897#issuecomment-338650717, and does seem to have been copied over to many other libraries.

This PR changes the values of a JsonRecord to also possibly be undefined, covering the fact that the key might not be set.

This does mean that it's possible to set keys as undefined, even though this type doesn't exist in JSON (stringify will throw these keys away). This actually fixes my problem in https://github.com/gcanti/io-ts/pull/628#issuecomment-1084597642 (which was complicated to try and get round in https://github.com/gcanti/io-ts/pull/639).

thewilkybarkid avatar Apr 06 '22 12:04 thewilkybarkid

dtslint failed in CI; locally it was only running up to TS 4.1. Looks like the library isn't pinned so I had an outdated version.

thewilkybarkid avatar Apr 06 '22 12:04 thewilkybarkid

The JsonRecord type currently allows you to access any string key, but this isn't type safe

IIRC there's a tsconfig option for that (noUncheckedIndexedAccess)

gcanti avatar Apr 12 '22 10:04 gcanti

@gcanti Ah, that's definitely something to enable generally (and does fix the accessing problem). Thanks.

It doesn't, however, get around https://github.com/gcanti/io-ts/pull/628#issuecomment-1084597642. Should I close this and reopen https://github.com/gcanti/io-ts/pull/639?

thewilkybarkid avatar Apr 12 '22 11:04 thewilkybarkid