Description
Describe the bug
Current type hint for onwarn
is as follows:
interface SvelteConfig {
onwarn?: (warning: Warning, defaultHandler?: (warning: Warning) => void) => void;
}
This type hint is wrong in that defaultHandler
is marked optional. With this definition, when writing vite.config.ts
with typescript strict
flag enabled, the onwarn
handler must handle the case of undefined
being passed as defaultHandler
argument.
const options = {
//...
onwarn: (warning, defaultHandler) => {
defaultHandler(warning); // ERROR: `defaultHandler` is possibly 'undefined'.
}
}
However, the defaultHandler
is always passed to the onwarn
handler.
The typescript error is because (1) (Warning, ((Warning) => void) | undefined) => void
is a subtype of (2) (Warning, (Warning => void)) => void
, not the other way around. So you can't pass (2) into a place that accepts (1).
Therefore, the correct type should be to remove the optional mark ?
from defaultHandler
. Such definition still accepts an onwarn
function without defaultHandler
parameter (warning) => void
.
c.f. https://www.typescriptlang.org/docs/handbook/type-compatibility.html#comparing-two-functions
tested here: https://stackblitz.com/edit/vitejs-vite-86jcat?file=typescript.ts
Note that the bug only occurs when the typescript strictFunctionTypes
flag, or strict
flag is enabled. Without it, the type system is relaxed so that a supertype function type can go into a place that accepts subtype function type. (https://www.typescriptlang.org/docs/handbook/type-compatibility.html#function-parameter-bivariance)
Reproduction URL
https://stackblitz.com/edit/vitejs-vite-86jcat?file=vite.config.ts
Reproduction
- Run
tsc --noEmit
in the terminal to typecheck using tsc
It throws an error that Cannot invoke an object which is possibly 'undefined'.
for the line defaultHandler(warning)
in vite.config.ts
.
export default defineConfig({
plugins: [
svelte({
onwarn: (warning, defaultHandler) => {
defaultHandler(warning); // ERROR!
},
}),
],
});
Logs
No response
System Info
System:
OS: Linux 5.0 undefined
CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 0 Bytes / 0 Bytes
Shell: 1.0 - /bin/jsh
Binaries:
Node: 18.18.0 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 10.2.3 - /usr/local/bin/npm
pnpm: 8.15.3 - /usr/local/bin/pnpm
npmPackages:
@sveltejs/vite-plugin-svelte: ^3.0.2 => 3.1.0
svelte: ^4.2.12 => 4.2.14
vite: ^5.2.8 => 5.2.8