[Typings] improve userEvent.type typings to only return a Promise when using delay is set
See original GitHub issueuserEvent.type
always returns a promise, but we only need to await it if we’re using the { delay: number }
as the third argument, according to the docs
// this returns a Promise, although it is not used
userEvent.type(getByRole('button'))
In js that’s fine, but in TS, the compiler or eslint might warn you about having floating promises.
that could force the TS users to always use await
even though it might not be necessary - it’s different from js where we could just not await it.
A possible solution could be to use type overloading when defining the function type
, so it returns Promise<void>
if { delay: number }
is passed, but no value is provided, return void
I think that could be achieved with the following code
type TypeWithoutDelay = (element: TargetElement, text: string, userOpts?: Omit<ITypeOpts, 'delay'> ) => void
type TypeWithDelay = (element: TargetElement, text: string, userOpts: Omit<ITypeOpts, 'delay'> & { delay: number }) => Promise<void>
// then on userEvent.type
declare const userEvent: {
//...
type: TypeWithDelay & TypeWithoutDelay
//...
}
That should allow the inference to work
skipping options
not passing delay
using delay: number
(which gives us the Promise as expected)
While this works, I wanted to read your thoughts as the code does return a Promise (instead of void), just that it is not required to be awaited, so it could be misleading, or perhaps it’s not worth the effort. I could do the PR as it is just as simple as updating the typings with that option.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:5
- Comments:6 (3 by maintainers)
Top GitHub Comments
I have committed @ljosberinn’s types from https://github.com/testing-library/user-event/issues/480#issuecomment-721288992 and added tests in #491.
Could also go a little bit more complex to catch the case where
delay: 0
is also synchronous, at the cost of showing something invalid for negative delays but a negative delay is technically nonsense: https://www.typescriptlang.org/play?#code/FAehAIBEFMDMEsB28Au8D2iDO4BGBPALnAHUBXcACQEN01rFwAeACxRQActCwBzVFmVwA6AMboAtiADubLAGt8APmDQAHh3QAnFOCQpoW2NVHRwASQAq+DtADyHFDgDewcOAXwOAYQA28UXkAfmJcdHRfaAY3D3kvAEEyFHQ-dCxoELxwyOj3ABNoX2p8TMQyCVxDGKRUeGpfAGVC6FE0TAaUah1S8sqtauR6RubWjEQAUUQ8noqqgF9gVQ1tXRQbM0su3mgUcciJaERdAF5wPegDo-AAH1IkPPRpRYLRIq0zcWxdMnStcYA3Q4oYiudxrWzEJiWcDqAxTHBWdYOJxKAAUMXczUuwPAmy0212+yBABoMeADGocVgUFokLxSe53D9DMisJkAEpRB6IXz4KFKBngACU4GOSlxMMphzyLnABSKRHAAAZwAtGeAguB-uh4HkycRobDpbL5cViGVZlpVWT3JqAApaSTwdJMbW6lTq9zEN16hbAF5vD6YankvYGrY7c7Y4CfEPOgBqOryovAzL+gKOwnB0FRhOJ4AA5LBwgX8845YUzcrVUKY8HdM6HU70im0wCgVn1rm9vmiyWyxWFcQAIwqua12MNrDxXxYdCJ3Wt37tzPZ7u+XvF9AF2ugCBIcRad6tcnrcDvFBkLSMXBJcD1OfgRB0c9RXy8++MJAcO8oFjUXQDgYHAGHwP86SCOsvj0adZ3QJsJGdMxTjbDMUE7Wx103ftwHLU1FQAWlHMchSAA