phillip-le / phillip-le.github.io

https://phillip-le.github.io/
1 stars 0 forks source link

Handling type safety with overloaded functions #95

Open phillip-le opened 2 months ago

phillip-le commented 2 months ago
import { sign } from 'node:crypto';

vi.mocked(sign as () => Buffer).mockReturnValueOnce(Buffer.from('hello'))

sign is a function with an overloaded function signature. It can return either Buffer or void depending on the function arguments given. By default, vi.mocked infers that sign is a mocked function that should return void.

I want to tell TypeScript that I should be returning a Buffer

Expect that type asserting sign as some other return type is valid e.g. sign as () => number should have the following error:

Conversion of type '{ (algorithm: string | null | undefined, data: ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): Buffer; (algorithm: string | ... 1 more ... | undefined, data: ArrayBufferView, key: KeyLike | ... 2 more ... | SignJsonWebKeyInput, callback: (error: Error | null, data: Bu...' to type '() => number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgZ2AcwHZwL5wGZQQhwDkGEAJgKYBcAxlAJ5gwQkBQoksicAbsBz5CxEgJhVkMDuwD0AKjjsAwhAx8qUVGrgQ8cGMyqkkACgCGAGzTRgMABYgaKGFGAY0cAD5wMAV0tLbzg-DGo8dyoKABo4CnMYc2cAQSgoc0YAIT88PE0ANWAqAHdYgGsqRmcAaUqAGWAK4PYAZXQMWsYAeQAjACsqOhgASQwwP3gfNswABTc+BKpO0fHJuGmMAClkNQB1Kh7lsYmASmds3M0AbjgLa1sHJxc3D2CAOg+4AEY4EGhjdgfN7BULhSIxOIJJJwVLpLI5PJQQolcqVGr1RrGHxAuAAJl+-zgOKm7W2ewOR1WsXYdCslh65joZWcpk0hCgzgAomloMF-IFYvFEuc-ECSAYIAYjKRTCc4ABeAB8vj8IB6mnFIAycHVcHMv2AUnMTXVtL8yGMGCodnsmilYAByARwDoRQwMEsjF0GiglnMYGQcGKNoMtt0Dk0wOG+gchqD5kD7gk7uAaissToah98AjcCoAA8wFBJNosKxSKEyuRihhxREtDA3ux5LI5LI4AABGDIAC0BYdQz7PKg7AEbz+TKiplQmD1gdlCuV-jVmhO44gTIASlQYH4oBh8lY-FRTABWE7sNud7t9wuDGBD9kwqBoVVUd26GPSkgXRHiuPkPACYzhg5g9JYxjlmA5jpCAO52no9rGGIEDABQJBvKYuIAMwACznqOwDrpOFDTu0a4TmU267vuh6WMepi-pGBBEKYJC2oEbAnBeV4AOIQJQSEoOYeSGIRxEVKRIFzrccpKnATFQBRG5UTue4HkeVBdBgdAnopbwsSAbEcZYXEnEAA