I'm having trouble writing a wrapper for an overloaded function.
The function I'm wrapping is the SendGrid email sending function. That function is overloaded like (simplified):
declare class MailService {
send(data: Email): foo;
send(data: Email[]): foo;
}
I want to write a function that can either accept an Email or Email[]. But when I do it like this, it complains that no overload matches the call:
function sendEmailWrapper1(data: Email | Email[]) {
sendGrid.send(data)
}
However, this works:
function sendEmailWrapper2(data: Email | Email[]) {
if ('length' in data) {
sendGrid.send(data)
} else {
sendGrid.send(data)
}
}
I think that what's happening is that Email | Email[] isn't a valid input for send(data: Email) or for send(data: Email[]), and Typescript doesn't realize that the overloads mean that sendGrid.send(data) should be valid (and, indeed, if the if and else branches can have the same code and be valid, that makes it seem like Typescript should be able to realize that the statement is valid even without an if statement to help it infer a type since Typescript is compile-time only and won't actually direct the runtime code execution to make different function calls based on the types).
My two questions:
- What's the best practice in situations like these?
- Is this just a shortcoming in the Typescript compiler, or is there a good reason that
sendEmailWrapper1would fail to compile butsendEmailWrapper2would work?
Thanks!