guide: Add section on working with duck-typed interfaces

This commit is contained in:
Nick Fitzgerald
2018-09-11 16:29:44 -07:00
parent a311c29f1d
commit 1872e84a8a
4 changed files with 27 additions and 3 deletions

View File

@ -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)

View File

@ -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}}
```