Type inference when using extend
in a generic is not consistent
#59993
Labels
Question
An issue which isn't directly actionable in code
π Search Terms
type inference when extend condition for a generic as const narrow inconsistent
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play/?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtVIEYAeAFQD4AKADwC54SBKOkgbgCgA3WeKA+AXkIUA5AAkQECDmEMW8APTz4AZwwwsqAOZs2oSLAQp02PEgBMpeCCoYQqYMpVqNmyrXpN67LjB5mB5iLiktKyCkoARMFSEfBEALTx8ADuABYAniqpOMgQwPAYqQjWtvbwYKlQWgiFCMlQmRjpAA4IWI4aiCAwcMAA-PCiOMnwwDjwAJLwyMo1ReV4wFgm+ABGyBjwALZQANZtm53dvTyOqupafTp60HBIaJi4+IgAzJYldg5OF5rwAD7wVDILarbpuZieVicbhQF4BV5BCRSGRyRTwKJInCxBJJQrteD42oqKBbBBQRxEqCrHAcEAAGng602ymyIyg01mYHJdQykxSOTyKSqmzxjlBlQ4uBg13At0MDxWSAALO8bJ8zs4tABtAC64I8zG8MKV8KVFC1Ykxwh1YTR5xcuriiRSvOUyGAoFQGAgmWWBMcqBwh1QXR6IHy5IWqFUV10soM92MTyQAFZVaUvtScBAQFVdfrGIbob4oCn4SnzYgoBBZjbUUoqzWQI60TiXZlI2AcMovUgcL4szmqmKNoCg33fPatB18KKOQgubM+kA
π» Code
π Actual behavior
The type inference is not consistent in the above cases, and it's unclear to me (a) what is the logic behind this, and (b) how do I accomplish a different behavior if I need it. More specifically:
extends string
means that the type is now inferred as const?as const
?extends string[]
andextends boolean[]
behaves so differently? Why booleans gets the const treatment while strings don't?π Expected behavior
Since there is a dedicated feature when we want
as const
for generics, I think that it should be inferred not as const in all of these use cases. This offers the maximum flexibility for consumers as they can pick the behavior they want.I would also be happy for any work around for this. Let's take this example:
How do I make it so that:
f('somestring')
is inferred as stringf<'blue' | 'red'>('red')
is inferred as `red'Also - how do I solve the issue with arrays? Specifically, if I have the function:
Can I make it so that
f(['string', true])
will be inferred as[string, boolean]
instead of[string, true]
?Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: