Support for ?
Suffix in TypeScript Definitions for Optional Parameters with #[wasm_bindgen(unchecked_param_type)]
#4412
Labels
Motivation
I'm using the new
#[wasm_bindgen(unchecked_param_type)]
from #4394 for an options object which is optional. But that seems to come with some issues.Let's say we have a function like this:
The intention here should be clear:
f
is a function that takes an optional parameter of typeMyOptions
, which is included via some other means.However, the output of this function in the TypeScript definitions would be:
This is missing the
?
suffix that is usually available for other optional values. Normally, it would generate:without the param type override.
I would really like to have it generate:
Proposed Solution
I see three options here:
Inspect the Param Type in
#[wasm_bindgen(unchecked_param_type)]
Allow the attribute to inspect the param type, and when it's
Option
, add the?
suffix. However, this would only work for types that implementOptionFromWasmAbi
, whichJsValue
does not implement. This limitation would make the attribute less useful overall.Modify
#[wasm_bindgen(unchecked_param_type)]
to Accept a ParameterAdd a parameter, such as
?
, to declare the param as optional. While this approach is flexible, it feels unintuitive because it adds complexity to the attribute's syntax.Add a New Attribute
Introduce a new attribute, such as
#[wasm_bindgen(unchecked_optional_param)]
, to explicitly mark a parameter as optional. This would be straightforward and would work even withJsValue
, as you could simply check forJsValue::is_undefined
to determine whether the value is set.I believe the third option, adding
#[wasm_bindgen(unchecked_optional_param)]
, is the most flexible and intuitive. It would address the issue without relying on the param type or modifying existing behavior.Alternatives
It may be possible to define overloaded functions using the
#[wasm_bindgen(js_name)]
attribute. However, now you have two function signatures, and you would need to duplicate your documentation to make it available at all relevant positions.I also tried passing a default value into the
#[wasm_bindgen(unchecked_param_type)]
call to trick TypeScript, but that doesn't work for.d.ts
files.Additional Context
Modern JavaScript libraries commonly use this structure when all fields in an
options
object are optional. Examples include:copy
function: copy optionsfetch
function: fetch optionscrypto.Hash.copy
method: Hash copy optionsThe text was updated successfully, but these errors were encountered: