diff --git a/examples/duck-typed-interfaces/README.md b/examples/duck-typed-interfaces/README.md index a5cf3773..5cd195e5 100644 --- a/examples/duck-typed-interfaces/README.md +++ b/examples/duck-typed-interfaces/README.md @@ -1,7 +1,6 @@ -# Canvas 2D Example +# Duck-Typed Interfaces Example -This directory is an example of using the `web-sys` crate to draw on a 2D -canvas. +This directory is an example of using duck-typed JS interfaces with `wasm-bindgen`. You can build and run the example with: diff --git a/guide/src/SUMMARY.md b/guide/src/SUMMARY.md index 016c5341..ee461f01 100644 --- a/guide/src/SUMMARY.md +++ b/guide/src/SUMMARY.md @@ -15,6 +15,7 @@ - [No ES Modules](./reference/no-esm.md) - [Arbitrary Data with Serde](./reference/arbitrary-data-with-serde.md) - [Accessing Properties of Untyped JS Values](./reference/accessing-properties-of-untyped-js-values.md) + - [Working with Duck-Typed Interfaces](./reference/working-with-duck-typed-interfaces.md) - [Command Line Interface](./reference/cli.md) - [Supported Types](./reference/types.md) - [Imported JavaScript Types](./reference/types/imported-js-types.md) diff --git a/guide/src/reference/accessing-properties-of-untyped-js-values.md b/guide/src/reference/accessing-properties-of-untyped-js-values.md index 20a18027..5acd128c 100644 --- a/guide/src/reference/accessing-properties-of-untyped-js-values.md +++ b/guide/src/reference/accessing-properties-of-untyped-js-values.md @@ -5,6 +5,10 @@ regardless if it is an `instanceof` some JavaScript class or not, use [the `js_sys::Reflect` APIs][js-sys-reflect]. These APIs are bindings to the [JavaScript builtin `Reflect` object][mdn-reflect] and its methods. +You might also benefit from [using duck-typed +interfaces](./working-with-duck-typed-interfaces.html) instead of working with +untyped values. + ## Reading Properties with `js_sys::Reflect::get` [API documentation for `js_sys::Reflect::get`.](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Reflect.html#method.get) diff --git a/guide/src/reference/working-with-duck-typed-interfaces.md b/guide/src/reference/working-with-duck-typed-interfaces.md new file mode 100644 index 00000000..a6bf2e7b --- /dev/null +++ b/guide/src/reference/working-with-duck-typed-interfaces.md @@ -0,0 +1,20 @@ +# Working with Duck-Typed Interfaces + +Liberal use of [the `structural` +attribute](./attributes/on-js-imports/structural.html) on imported methods, +getters, and setters allows you to define duck-typed interfaces. A duck-typed +interface is one where many different JavaScript objects that don't share the +same base class in their prototype chain and therefore are not `instanceof` the +same base can be used the same way. + +## Defining a Duck-Typed Interface in Rust + +```rust +{{#include ../../../examples/duck-typed-interfaces/src/lib.rs}} +``` + +## JavaScript Usage + +```js +{{#include ../../../examples/duck-typed-interfaces/duck-typed-interfaces.js}} +```