Closed castarco closed 2 months ago
Duplicate of #34692.
@MartinJohns thank you for pointing that one out. There's one detail, though, that makes me wonder if it's exactly the same.
const
-declared values for some reasons I list in this same issue, while the other issue does not make any distinction.Well, I'll close it anyway. I'll leave a reference to my comments there.
π Search Terms
β Viability Checklist
β Suggestion
I think it would be nice if TypeScript was able to narrow down the type for
length
property of const string literals.Right now, we have the following:
What I'd expect is something like:
Some details to take into account:
string
values are immutable, leaving aside tons of potential interactions with "intrinsics", it should be easier to implement than narrowed-downlength
's type forreadonly
arrays (from my probably naive perspective).const
values. Althoughstring
is immutable, a variable declared withlet
orvar
could change where is pointing to, therefore invalidating the type-inferred length.Some "aesthetic" reasons for wanting this feature that don't fit as "motivating example" nor "use case":
π Motivating Example
Case 1: Constrained Assignments & Function Parameters
While we can create type guard functions to ensure the length of a string, relying on much simpler conditional type guards does not work well. This is an entirely different problem than the one I'm pointing at, but still relevant, listed here for convenience (wait for the second part of this case, where I reach the point I really want to mention):
As I was saying, we can write function type guards... but they only let us set types for "outputs", assignments are a completely different beast:
The known alternatives are:
as
. This option adds extra work, and is too brittle.Case 2: More powerful Template Literals without RegExp nor combinatory explosions
There are many open issues asking for regular expressions or similar mechanisms embedded into template literals. There are also sound reasons to not rush any feature in that direction :
On the other hand, and in the absence of anything resembling regular expressions for string templates, many people have tried going through more "hacky" paths. The basic idea is simple, but it fails miserably. Let's use UUIDs as an hexample:
Although it wouldn't be as powerful as having character subsets nor regular expressions, being able to force a specific length for "open ended" string template types would make it possible to introduce tons of "cheap" type refinements:
This is not the only alternative, though. I really don't know enough about how string template types are implemented, but one (very theoretical, and probably wrong) possibility would be to avoid computing the whole extension of the type, and only checking for type matches instance by instance (or to provide a "manual" way to avoid computing the extension of the type, in case doing that for all cases introduced regressions of any kind).
π» Use Cases