TypeScript: When trying to use mapped tuples as rest parameters error 'A rest parameter must be of an array type' given
TypeScript Version: 3.2
Search Terms: mapped tuples rest
Code
type FuncParams<T> = T extends (...args: infer P) => any ? P : never;
type Stringify<T> = {
[K in keyof T]: string;
};
type Optional<T> = {
[K in keyof T]?: T[K];
};
type ThreeParamFunc = (paramOne: string, paramTwo: number, paramThree: boolean) => void;
type Params = FuncParams<ThreeParamFunc>; // [string, number, boolean]
type StringParams = Stringify<FuncParams<ThreeParamFunc>>; // [string, string, string]
type OptionalParams = Optional<FuncParams<ThreeParamFunc>>; // [string?, number?, boolean?]
function doStuff<T>(func: T, ...params: FuncParams<T>) { // works fine
}
function doOptionalStuff<T>(func: T, ...params: Optional<FuncParams<T>>) { // A rest parameter must be of an array type.
}
function doStringStuff<T>(func: T, ...params: Stringify<FuncParams<T>>) { // A rest parameter must be of an array type.
}
Expected behavior: I should be able to use a mapped tuple as a rest param in a function
Actual behavior:
I get the error A rest parameter must be of an array type.
Playground Link: Link
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 26
- Comments: 18 (5 by maintainers)
Commits related to this issue
- Accept new baselines (break is due to #29919) — committed to microsoft/TypeScript by ahejlsberg 5 months ago
I’d be interested to hear why this is marked as a suggestion rather than a bug. As far as I see it you can usually use a tuple type as a function parameter but in this scenario (and other similarly complicated scenarios) it doesn’t work.
Can anyone explain why it doesn’t work in this case? I have tested my mapped type with function parameters and on it’s own it works fine as a rest param:
playground
The issue still exists on typescript 4.5.4. In my case applying generics directly on inferred parameters instead of
Parameters<T>
will fix this error, and I’ve checked they are actually the same typeplayground
Same error when using builtin
Parameters
andPartial
:Error is there, though actual type is resolved properly. Playground
Having the same problem - prepared a simpler repro (with artificial code ofc).
Real world use case would be to cover reselect’s createSelector API in generic manner - https://github.com/reduxjs/reselect#createselectorinputselectors--inputselectors-resultfunc
I bisected this particular change that @freshgum-bubbles mentioned to this diff and further down to my own PR: https://github.com/microsoft/TypeScript/pull/49947
…and now I realized that this PR was referencing this exact test case 😅 it’s just that it didn’t fix this issue as a whole
I was about to raise a new issue, but it sounds like the same issue as described in the last comments? Playground
@RyanCavanaugh this is marked as a “suggestion” but I think it’s actually a bug.