Open leaumar opened 1 year ago
// @chrisvasz
This appears to be a Typescript bug: https://github.com/microsoft/TypeScript/issues/17002. Looks like the best recommendation in that thread is to override the type definition of Array.isArray
. That recommendation may or may not be acceptable for consumers of this library though. Alternatively, we could restore the previous implementation of JsonValue, then add a ReadonlyJsonValue
type that accepts ReadonlyArrays. Thoughts?
It seems a very different issue to me, it's about losing the readonly
part of the array type when it is an array. If you ask me, Array.isArray
should say that a readonly x[]
is an array just the same, type-wise. Making a helper function that expands Array.isArray
's type a bit seems to work. Note how the type of data
isn't just JsonValue[]
anymore but the whole JsonArray
(though it doesn't combine the other types into JsonPrimitive
the same way):
Perhaps a helper function in type-fest for each of the Json types? isJsonPrimitive
, isJsonArray
, and isJsonObject
to narrow the general JsonValue
?
I think this change on JsonValue
would ideally be reverted and ReadonlyDeep<JsonValue>
could be used for restricting mutability. The problem with reverting this is that projects probably already depend on this behavior. An alternative could be adding JsonValueWriteable
which doesn't include the readonly array. This could provide an straightforward upgrade path for projects which are behind on versions.
Exporting a utility function is not a good solution for the following reasons:
readonly T[]
and T[]
cannot be distinguished by a type predicate at runtime (you'll never be able to narrow past readonly T[] | T[]
in a meaningful way)readonly T[] | T[]
is identical to readonly T[]
in most waysArray.isArray
with a custom isArray
function or do module augmentation patches across 6 different packages in my monorepo (and I suspect other people with large codebases won't enjoy this too)Array.isArray
to any[]
kind of makes sense as it is - it doesn't limit mutability, which is a sensible default
Trying to update type-fest to 3.5.4 yields the following breakage:
An
Array.isArray(JsonValue)
guard removesJsonValue[]
but notreadonly JsonValue[]
from the type. Is there a non-hacky solution (i.e. no manual type overrides) or could #549 be reverted and achieved a different way?Upvote & Fund