Type definition of `PyodideInterface.FS` is wrong
🐛 Bug
-
The current type definition of
PyodideInterface.FSis not perfect. Before 0.27.0,PyodideInterface.FSwas typed asanyso we could use any Emscripten FS methods without type errors (and without type checking) as below.const fileAsText: string = pyodide.FS.readFile(path, { encoding: "utf8" }); // ... if (pyodide.FS.analyzePath(dirPath).exists) { // ...Since 0.27.0, however,
PyodideInterface.FSis typed but the type definition doesn't contain all the methods and their signatures; For example,FS.analyzePath()is not defined.FS.readFile()is defined but its signature with the 2nd argument asreadFile(path, opts)is not defined. So some code that worked before started to fail type checking. This can be considered as being degraded. -
Even worse, (probably due to my poor TypeScript skill though,) I couldn't patch the type hint extending the module definition in an ambient type definition file like below. So I couldn't workaround this issue on my end.
// pyodide-override.d.ts
import "pyodide";
declare module "pyodide" {
interface FS {
readFile(path: string, options: { "utf8": string }): string;
readFile(path: string, options?: unknown): Uint8Array | string;
}
}
#5025 might be the context.
To Reproduce
import { loadPyodide } from "pyodide";
async function main() {
const pyodide = await loadPyodide();
pyodide.FS.writeFile("test.txt", "Hello", { encoding: "utf8" })
console.log(pyodide.FS.analyzePath("text.txt"))
console.log(pyodide.FS.readFile("test.txt", { encoding: "utf8" }));
}
main();
This code emits an error at type checking, but it works at runtime after transpiling with // @ts-ignore.
Expected behavior
The example above doesn't emit the type error.
- It's the best if the Pyodide package contains the perfect type definition.
- If it's not possible, it's better that
PyodideInterface.FSis typed asanyrather than the incomplete type hints. - Providing a way for the user to override the type definition with
d.tsfile is also an option if the core team can't be responsible for the complete type definition ofPyodideInterface.FS.
Environment
- Pyodide Version: 0.27.2
Additional context
Thanks for the report @whitphx.
I agree we should improve the type definition, but as Emscripten is written in JS, and DefinitelyTypes/Emscripten is a bit outdated, so it is difficult for us to keep it updated. Anyway, a PR to improve the typing is welcome.
Meanwhile, a workaround, for now, would be casting Pyodide.FS to any explicitly.
We recently adopted DefinitelyTyped/Emscripten for FS type, thanks to @R3gardless. So the IDEs should be able to use types from DefinitelyTyped/Emscripten.