You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allowing infer after extends T in conditional types would simplify complicated type definitions massively #47330
Doing this would allow the complete removal of an entire branch, and it's much more intuitive (the hanging infer stumped me a whole lot when I was learning).
Before:
InferringType<T> = T extends infer U ? U extends SomeConcreteType ? U : never : never
After:
InferringType<T> = T extends SomeConcreteType infer U ? U : never
Alternatives
Something consistent with the as keyword in template string literal types e.g.
InferringType<T> = T extends SomeConcreteType as U ? U : never
No extra syntax, just smart control flow analysis on the type variable.
InferringType<T> = T extends SomeConcreteType
? T // T extends SomeConcreteType on this branch
: never // T does not extend SomeConcreteType on this branch
📃 Motivating Example
This playground link - has some documentation that should provide some context for the following code, but this is a pretty universal pattern anyway.
Before:
typeInferEventFromTypeMatch<TypeMatchextendsstring>=TypeMatchextends infer InferredTypeMatch
? InferredTypeMatchextendsEvent['type']
? Extract<Event,AbstractEvent<InferredTypeMatch,any>>
: InferredTypeMatchextends `${infer WildcardedTypeMatch}*`
? Eventextends infer EventCase
? EventCaseextends{type: `${WildcardedTypeMatch}${any}` }
? EventCase
: never
: never
: never
: never
After:
typeInferEventFromTypeMatch0<TypeMatchStringextendsstring>=TypeMatchStringextendsEvent['type'] infer ExactTypeMatchString// Can give a much more meaningful label
? Extract<Event,AbstractEvent<ExactTypeMatchString,any>>
: InferredTypeMatchextends `${infer WildcardedTypeMatch}*`
? Eventextends{type: `${WildcardedTypeMatch}${any}` } infer WildcardTypeMatch// Can give a much more meaningful label here too
? WildcardTypeMatch
: never
: never// Only two hanging nevers, rather than four
I think what you're looking for already exists, with a slightly different syntax:
typeIs<TextendsU,U>=T
Translating your second version directly:
typeIs<TextendsU,U>=T;typeInferEventFromTypeMatch<TypeMatchStringextendsstring>=TypeMatchStringextendsIs<infer ExactTypeMatchString,Event['type']>// Can give a much more meaningful label
? Extract<Event,AbstractEvent<ExactTypeMatchString,any>>
: TypeMatchStringextends `${infer WildcardedTypeMatch}*`
? EventextendsIs<infer WildcardTypeMatch,{type: `${WildcardedTypeMatch}${any}` }>// Can give a much more meaningful label here too
? WildcardTypeMatch
: never
: never// Only two hanging nevers, rather than four
But in your specific example you don't need it at all:
typeInferEventFromTypeMatch<TypeMatchStringextendsstring>=TypeMatchStringextendsEvent['type']// Can give a much more meaningful label
? Extract<Event,AbstractEvent<TypeMatchString,any>>
: TypeMatchStringextends `${infer WildcardedTypeMatch}*`
? Eventextends{type: `${WildcardedTypeMatch}${any}` }// Can give a much more meaningful label here too
? Event
: never
: never// Only two hanging nevers, rather than four
There's a cost to inference, so in idiomatic code we do not use it to rename types. Narrowing a type with T extends Something and then using T is not hard to follow, once you get used to it.
typeTestable={test(): void};typeGetTest<TextendsTestable>={m: T};// Nothing needed here to match the constrainttypeFoo<T>=TextendsTestable ? GetTest<T> : never;
A more straightforward motivating example would be helpful here.
tl;dr I need this feature as well but for a different reason. This feature can help us avoid reaching the recursion depth limit.
I came across this issue while searching for a duplicate of what I was going to submit.
Narrowing a type with T extends Something and then using T is not hard to follow, once you get used to it.
I agree with this. Renaming type parameters won't affect readability much once you learn the syntax of conditional type. That said, I still find this feature useful to mitigate the compiler's recursion depth limit. Let me illustrate the problem I'm having right now.
In the example below (playground), DottedKey receives one object type parameter and resolves to a union of all the possible property access chained with a dot.
While this works as expected with simple types, giving complex types yields a compile error TS2589: Type instantiation is excessively deep and possibly infinite.. I want to use DottedKey with the constituents of @types/estree's Node, and they are complex enough to cause the error.
I've confirmed that removing at least one conditional type in DottedKey fixes the error in my use case, but they are all required including the seemingly redundant T[K] extends infer V, which enables union distribution. So I can't go that way.
I thought the following patch could be a workaround, but it didn't help. Unwanted literals such as foo.bar.charAt become assignable to T0. This comes from the fact that [T[K], T[K]] extends [Record<string, any>, infer V] somehow evaluates to true when T is {bar: string} (reproduction). I haven't figured out why yet.
@@ -1,9 +1,7 @@
type DottedKey<T, K extends keyof T = keyof T> = K extends string
- ? T[K] extends Record<string, any>- ? T[K] extends infer V+ ? [T[K], T[K]] extends [Record<string, any>, infer V]
? V extends (infer E)[]
? K | `${K}.${number | "length"}` | `${K}.${number}.${DottedKey<E>}`
: K | `${K}.${DottedKey<V>}`
- : never
: K
That's why I need this feature. If something like T[K] extends Records<string, any> infer V (open to better syntax ideas) is available, recursion depth won't hit its limit without breaking the definition of DottedKey.
Ryan Cavanaugh (@RyanCavanaugh) Is this straightforward and motivating? Please let me know if there is any room for further elaboration.
Ryan Cavanaugh (@RyanCavanaugh) I don't want the distributivity behavior to be changed. Let me rephrase my issue and possible solutions.
My original DottedKey implementation has 4 nested conditional types and I want to reduce the number to 3 or less. My workaround in the previous comment would have reduced it to 3, but it is not working unfortunately.
The feature requested by the issue author will also reduce the number of conditional types. [T[K], T[K]] extends [Record<string, any>, infer V] will be replaced with something like T[K] extends Record<string, any> infer V.
In both cases, the nest depth is reduced to 3 and I still have a type parameter V, which can be distributive in a conditional type (unlike T[K]).
q: is there any info anywhere on what T extends infer R ? R : never does and how it affects other parts of the inference algorithm? Intuitively I've assumed that it's forcing the compiler to resolve T based on the information it was able to gather.
I've assumed that in a situation like this it wouldn't have any effect on how typechecking works for the argument that should be typechecked with the outcome of ComputeStuff:
Unfortunately, it changes the behavior "down the road" but since tsTypes is an optional property I also need to "resolve" it quickly to TypegenDisabled case, and while this trick works for that, some other test cases of mine break due to the mentioned change of behavior.
This is just an example to illustrate what I'm doing but I'm really after "fixing" it - I would like to better understand how I could influence the order in which TS infers stuff. Basically, I know where the information I need is in the input arguments but I'm not sure how to best control what should be "deferred" by TS. Note that I'm aware of NoInfer, LowInfer, and other stuff but this is still just a magic box that I find hard to manage in a complex scenario.
I realize the pull request is useful for cases like this:
typeStringBox<Textendsstring>={x:T};typeFirstIfString<T>=Textends[infer S, ...unknown[]]
? StringBox<S&string>
: never;typeFirstIfString2<T>=Textends[infer Sextendsstring, ...unknown[]]
? StringBox<S>
: never;typeFirstIfString2Alt<T>=Textends[infer S, ...unknown[]]
? Sextendsstring
? StringBox<S>
: never
: never;typeD=FirstIfString<[boolean,number,string]>;// { x: never }typeD2=FirstIfString2<[boolean,number,string]>;// nevertypeD3=FirstIfString2Alt<[boolean,number,string]>;// never
They really should have put a better example in the announcement.
Update: actually, isn't this even simpler?
typeStringBox<Textendsstring>={x:T};typeFirstIfString<T>=Textendsany[]
? T[0]extendsstring
? StringBox<T[0]>// T[0] in original example
: never
: never;
Ryan Cavanaugh (@RyanCavanaugh) I think this is basically solved by the mentioned #48112 - the only difference is in the allowed order between infer and extra extends. The OP's example can be rewritten (using the added capability) as follows:
Sorry, I didn't notice your post. Either way, there are different ways to write this type - the point is (also mentioned by you) that infer+extends combination (almost like proposed by the OP) is already available.
#48112 resolves the issue in the original post, but perhaps the recursionlimit issue mentioned in the comments should be resolved (perhaps this issue should be closed as complete, and the recursion limit should be opened as a new issue?).
As OP's motivating example can be rewritten without the new feature infer A extends B, which I mentioned in my comments before I realized that @webstrand's earlier comment had already mentioned it, I don't feel it is a good motivating example. There are better examples in this comment at #48112.
Activity
webstrand commentedon Jan 6, 2022
I think what you're looking for already exists, with a slightly different syntax:
Translating your second version directly:
But in your specific example you don't need it at all:
There's a cost to inference, so in idiomatic code we do not use it to rename types. Narrowing a type with
T extends Somethingand then usingTis not hard to follow, once you get used to it.RyanCavanaugh commentedon Jan 12, 2022
This is already how it works?
A more straightforward motivating example would be helpful here.
yudai-nkt commentedon Feb 3, 2022
tl;dr I need this feature as well but for a different reason. This feature can help us avoid reaching the recursion depth limit.
I came across this issue while searching for a duplicate of what I was going to submit.
I agree with this. Renaming type parameters won't affect readability much once you learn the syntax of conditional type. That said, I still find this feature useful to mitigate the compiler's recursion depth limit. Let me illustrate the problem I'm having right now.
In the example below (playground),
DottedKeyreceives one object type parameter and resolves to a union of all the possible property access chained with a dot.While this works as expected with simple types, giving complex types yields a compile error
TS2589: Type instantiation is excessively deep and possibly infinite.. I want to useDottedKeywith the constituents of@types/estree'sNode, and they are complex enough to cause the error.I've confirmed that removing at least one conditional type in
DottedKeyfixes the error in my use case, but they are all required including the seemingly redundantT[K] extends infer V, which enables union distribution. So I can't go that way.I thought the following patch could be a workaround, but it didn't help. Unwanted literals such as
foo.bar.charAtbecome assignable toT0. This comes from the fact that[T[K], T[K]] extends [Record<string, any>, infer V]somehow evaluates to true whenTis{bar: string}(reproduction). I haven't figured out why yet.That's why I need this feature. If something like
T[K] extends Records<string, any> infer V(open to better syntax ideas) is available, recursion depth won't hit its limit without breaking the definition ofDottedKey.Ryan Cavanaugh (@RyanCavanaugh) Is this straightforward and motivating? Please let me know if there is any room for further elaboration.
RyanCavanaugh commentedon Feb 3, 2022
Yudai Nakata (@yudai-nkt) I think this a misunderstanding - almost certainly, we wouldn't change the distributivity behavior under this construct
yudai-nkt commentedon Feb 3, 2022
Ryan Cavanaugh (@RyanCavanaugh) I don't want the distributivity behavior to be changed. Let me rephrase my issue and possible solutions.
My original
DottedKeyimplementation has 4 nested conditional types and I want to reduce the number to 3 or less. My workaround in the previous comment would have reduced it to 3, but it is not working unfortunately.The feature requested by the issue author will also reduce the number of conditional types.
[T[K], T[K]] extends [Record<string, any>, infer V]will be replaced with something likeT[K] extends Record<string, any> infer V.In both cases, the nest depth is reduced to 3 and I still have a type parameter
V, which can be distributive in a conditional type (unlikeT[K]).RyanCavanaugh commentedon Feb 3, 2022
Sure, but nothing is going to make
DottedKeynot fail on at least some types.yudai-nkt commentedon Feb 4, 2022
Yes, but
Mdoesn't need to be covered byDottedKeyfor my specific use case. So I don't really care at the moment.Andarist commentedon Feb 25, 2022
q: is there any info anywhere on what
T extends infer R ? R : neverdoes and how it affects other parts of the inference algorithm? Intuitively I've assumed that it's forcing the compiler to resolve T based on the information it was able to gather.I've assumed that in a situation like this it wouldn't have any effect on how typechecking works for the argument that should be typechecked with the outcome of
ComputeStuff:Unfortunately, it changes the behavior "down the road" but since
tsTypesis an optional property I also need to "resolve" it quickly toTypegenDisabledcase, and while this trick works for that, some other test cases of mine break due to the mentioned change of behavior.This is just an example to illustrate what I'm doing but I'm really after "fixing" it - I would like to better understand how I could influence the order in which TS infers stuff. Basically, I know where the information I need is in the input arguments but I'm not sure how to best control what should be "deferred" by TS. Note that I'm aware of
NoInfer,LowInfer, and other stuff but this is still just a magic box that I find hard to manage in a complex scenario.yudai-nkt commentedon Apr 29, 2022
I'm trying 4.7 beta and it looks like #48112 fixes this issue although recursion limit is not relaxed yet.
theonlypwner commentedon Jul 13, 2022
I'm trying to understand the motivation behind this issue and #48112.
Considering the first post of this issue, what's the difference between
U extends SomeConcreteType ? U : neverandU & SomeConcreteType?Before:
After:
And in the Motivating Example, isn't it equivalent to this?
The announcement for #48112 has an example of 3 equivalent declarations, the last one of which is added by the pull request:
Isn't that also equivalent to this?
I realize the pull request is useful for cases like this:
They really should have put a better example in the announcement.
Update: actually, isn't this even simpler?
Andarist commentedon Mar 10, 2023
Ryan Cavanaugh (@RyanCavanaugh) I think this is basically solved by the mentioned #48112 - the only difference is in the allowed order between
inferand extraextends. The OP's example can be rewritten (using the added capability) as follows:TS playground with the full thing
theonlypwner commentedon Mar 10, 2023
How is this different from my example?
Also, OP's example doesn't have the extra
/characters in the strings.I tried rewriting OP's example, and I ended up with
This is the same as my past version, except
and
theonlypwner commentedon Mar 10, 2023
It seems to work if we rewrite to an alternate
DottedKeyA: (playground)Andarist commentedon Mar 11, 2023
Sorry, I didn't notice your post. Either way, there are different ways to write this type - the point is (also mentioned by you) that
infer+extendscombination (almost like proposed by the OP) is already available.theonlypwner commentedon Mar 14, 2023
#48112 resolves the issue in the original post, but perhaps the recursion limit issue mentioned in the comments should be resolved (perhaps this issue should be closed as complete, and the recursion limit should be opened as a new issue?).
As OP's motivating example can be rewritten without the new feature
infer A extends B, which I mentioned in my comments before I realized that @webstrand's earlier comment had already mentioned it, I don't feel it is a good motivating example. There are better examples in this comment at #48112.Andarist commentedon Mar 14, 2023
I think that the recursion limit issue is mostly mitigated by the ability to write tail recursive conditional types:
TS playground