ExcludeRestElement: Fix generic assignability with arrays#1274
ExcludeRestElement: Fix generic assignability with arrays#1274sindresorhus merged 4 commits intomainfrom
ExcludeRestElement: Fix generic assignability with arrays#1274Conversation
ad12bdd to
dc490d4
Compare
| : [...Result[0], ...Result[2]] | ||
| : Result | ||
| : never; | ||
| : never |
There was a problem hiding this comment.
If this is Result (and not never), then the compiler thinks the type produces something more than just arrays.
This comment was marked as outdated.
This comment was marked as outdated.
ffaeaf4 to
dc490d4
Compare
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as spam.
This comment was marked as spam.
| export type ExcludeRestElement<Array_ extends UnknownArray> = IfNotAnyOrNever<Array_, | ||
| SplitOnRestElement<Array_> extends infer Result | ||
| ? Result extends readonly UnknownArray[] | ||
| ? IsArrayReadonly<Array_> extends true | ||
| ? Readonly<[...Result[0], ...Result[2]]> | ||
| : [...Result[0], ...Result[2]] | ||
| : Result | ||
| : never; | ||
| : never | ||
| : never | ||
| >; |
There was a problem hiding this comment.
Please consider using IsAnyOrNever instead, as it provides more reliable handling for recursive types.
Refer my #1192 comment, and your #1266 comment regarding If* types.
| export type ExcludeRestElement<Array_ extends UnknownArray> = IfNotAnyOrNever<Array_, | |
| SplitOnRestElement<Array_> extends infer Result | |
| ? Result extends readonly UnknownArray[] | |
| ? IsArrayReadonly<Array_> extends true | |
| ? Readonly<[...Result[0], ...Result[2]]> | |
| : [...Result[0], ...Result[2]] | |
| : Result | |
| : never; | |
| : never | |
| : never | |
| >; | |
| export type ExcludeRestElement<Array_ extends UnknownArray> = | |
| IsAnyOrNever<Array_> extends true ? Array_ | |
| : SplitOnRestElement<Array_> extends infer Result | |
| ? Result extends readonly UnknownArray[] | |
| ? IsArrayReadonly<Array_> extends true | |
| ? Readonly<[...Result[0], ...Result[2]]> | |
| : [...Result[0], ...Result[2]] | |
| : never | |
| : never; |
There was a problem hiding this comment.
IfNotAnyOrNever works perfectly fine in this case because ExcludeRestElement is not a recursive type. Added test cases for long tuples in #0aed831.
your #1266 comment regarding
If*types.
This was only for recursive types.
There was a problem hiding this comment.
And, if used properly, IfNotAnyOrNever can even be used with recursive types without any problems. Added a note in #1276.
Currently, instantiations of
ExcludeRestElementwith generic types are not assignable toreadonly unknown[], this PR fixes this issue.This issue is also related to #1166 (comment). In general, it's better to handle
anyandnevercases explicitly.