wasm-bindgen
wasm-bindgen copied to clipboard
Allow creating a `T | null` type
Motivation
This has been talked about in bunch of issues already (#1252, #2139, #1906 and more), but I couldn't find a current issue describing this specific issue: returning T | null
instead of T | undefined
in generated types for a Rust Option<T>
type.
Proposed Solution
Either allow specifying the Typescript on a per-function basis (as described in comment to #1691) or introduce some kind of OptionNull<T>
type. Even more interesting would be some kind of Union<T, JsValue::Null>
type (reusable for other union type returning functions), but not sure how complicated that would get it.
Alternatives
There is the workaround of specifying a custom TS type with a custom section described at #1691, but that feels complicated for such a small thing that is sure to appear a lot in strictly typed code. I'm not sure the workaround even works when creating methods to Rust-defined JS-exported structs, in which case something even uglier (imo) is needed: https://github.com/rustwasm/wasm-bindgen/issues/2155#issuecomment-633568946
I mean, I don't at all have a say in this matter, but I don't see any value added by this. What are you gaining by this? Optional Parameters in Typescript are always defined as an T | undefined
union. Why decide to handle returns differently?
Emscripten seems to check the value is undefined or null,
For example, CanvasKit has the parameter type Shader | null
for setting shader https://github.com/google/skia/blob/main/modules/canvaskit/npm_build/types/index.d.ts#L2158 , and it makes error when I put undefined there.
And they did just bind that to cpp function using emscripten https://github.com/google/skia/blob/main/modules/canvaskit/canvaskit_bindings.cpp#L1668
So for me it's very useful if wasm-bindgen supports T | null
type.
What kind of error? A runtime error or a typescript error? You were showing a type definition. You can get around that with just casting the return value without runtime overhead, or you could go the suggested alternate route.
If it actually needs null then yeah perhaps it has a small impact, but at the same time I'm not certain there isn't an easy way to do it yourself.
A runtime error, not typescript error. I can't cast without overhead because I use wasm-bindgen, not javascript. I call it from my rust code.
If it's a runtime error casting on the TS side would not help in any case.
I still don't have any say in that matter, but this seems like something I could much more so see as a value add.
Though perhaps it's a different issue. At the very least the alternative in OPs post won't work for you as it's essentially the equivalent of casting the type on the TS side.
does this issue has any new progress?