Can you create types with dynamic literals?
Say I have this function:
With this I'm trying to create types with literals but I don't know those literals until runtime.
If I run:
It creates type:
But instead what I'm actually wanting is:
Which produces the correct type:
22 Replies
Try:
This is a good approach but also keep in mind I'll be shipping native generics soon to make this more intuitive
as const
still causes it to be string
I'll try narrow and pipeAhh oh well I wasn't sure. Let me take a look I know I did some exploration of which strategies like this TS liked
Oh wait
You reassigned to string
That is why it doesn't work
This produces:
Realistically
'${string}'
could validate but doesn't currently
That would be the easiest thing
For now you can just do this to work around it:
Even without the cast it actually is inferred correctly it just doesn't like the validation so you could also ignore the error or something if you wanted
When you reassign a variable with an explicit type like this:
Whatever previous narrowed type it had is erased, in this case the association with the generic parameterOk yes that works
I guess I can't guarantee
'${string}'
is valid because it could have single quotes
MehSeems to behave differently within
scope
:
This type is valid:
However, this doesn't work:
It becomes:
It still looks right to me, it doesn't make sense to have the type be something specific inside the function
hmm. It's working for me without the scope, but I'm getting type error when using scope:
You'll have to send a full repro
I don't see a point in creating that intermediate type in the inner function
I don't know why TS simplifies it when using
Type
but not Scope, but it doesn't seem like something that could be changed externally.
I'd also say if you're working with generics and nested functions this complex it's probably best to not worry about casting too much as even with no dependencies involved TS has a lot of limitations in that regard
Maybe the example is more complex so you need the nested scope in the function, but if not you could also consider just using chaining and composition to build your types
E.g. in a case like this you could use:
I don't need the explicit return type there, I was only adding it to make sure my function was returning the correct type. If I infer it after creation then it's as I expect:
For some reason it doesn't think the type types match when they do
Yeah best not to worry about it haha
Like worry the external result is correct
But trying to get correct inference in those intermediate steps will not always be possible