Given this JavaScript function:
function foo({ a, b, c = a + b }) {
return c * 2;
}
When I try to annotate it with types in typescript like this:
function foo({ a, b, c = a + b }: { a?: number, b?: number, c: number }): number {
return c * 2;
}
I get the error: TS2532 Object is possibly undefined which makes sense, because I haven't told it yet that a and b are not optional when c is not specified.
However any attempts to specify this didn't work:
- Overloading (1):
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number;
function foo({ c }: { c: number }): number {
return c * 2;
}
TS2371: A parameter initializer is only allowed in a function or constructor implementation.
- Overloading (2):
function foo({ c }: { c: number }): number;
function foo({ a, b, c = a + b }: { a: number; b: number; c: number }): number {
return c * 2;
}
TS2394: This overload signature is not compatible with its implementation signature.
This doesn't make sense to me, I don't see hhy TypeScript thinks that they are not compatible.
- Conditionals
function foo({
a,
b,
c = a + b,
}: {
a: typeof c extends number ? void : number;
b: typeof c extends number ? void : number;
c: typeof a extends number ? void : typeof b extends number ? void : number;
}): number {
return c * 2;
}
TS2502: 'a' is referenced directly or indirectly in its own type annotation.
TS2502: 'c' is referenced directly or indirectly in its own type annotation.
This makes sense, given that TypeScript is not able to solve for the recursion.
Does anyone know how this function could be strong-typed?
Note: I am very much aware that you can just change the prototype itself to have a different argument structure, but that would defeat the point of this exercise.