This doesn't compile (playground):
function myFunction(params: {
a: Date,
b?: Date
}) {
if (params.b) {
myFunctionInternal(params); // ERROR!
}
}
function myFunctionInternal(params: {
a: Date,
b: Date
}) {}
Is there a more elegant workaround than params as any
?
The problem is that the type guard impacts just the type of the field (
params.b
will have theundefined
removed) not the type of whole object (param
will continue to have the type{ a: Date, b?: Date }
)Not sure I would call it more elegant, but we can create a type guard that removes the undefined from a type field:
We could even create a version that takes any number of keys:
the error message said property 'b' is optional in type '{ a: Date; b?: Date; }' but required in type '{ a: Date; b: Date; }'
It can be solve like this
or