In the following code typescript complains that the argument does not match the called function.
In general that is ok, but in this case the type of emailType
and args
are bound to the same generic type T
so it should not error. As you can see in the following lines, if you fix the type T to some concrete value, e.g. "Foo"
typescript correctly recognizes that the types match.
- Is there either a way to tell typescript that the types match (without a
as any
assertion)? - Do you know of a better pattern to this problem? I really like it, because it makes calling
sendMail
convenient as you have intellisense for the emailType, which makes it easy to see which emails are available, and then intellisense for the required data to send the email.
const mails = {
Foo: (args: { foo: string }) => "",
Bar: (args: { bar: string }) => "",
}
function sendMail<T extends keyof typeof mails>(emailType: T, args: Parameters<typeof mails[T]>[0]){
mails[emailType](args) // ERROR: Argument of type '{ foo: string; } | { bar: string; }' is not assignable to parameter of type '{ foo: string; } & { bar: string; }'
mails[emailType as "Foo"](args as Parameters<typeof mails["Foo"]>[0]) // works
mails[emailType as "Bar"](args as Parameters<typeof mails["Bar"]>[0]) // works
}
Aucun commentaire:
Enregistrer un commentaire