Skip to content

Add %external() class feature detection example #361

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions pages/docs/manual/latest/bind-to-global-js-values.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,36 @@ if (match !== undefined) {

</CodeTab>

This approach may also be used for JS class feature detection.

Note that here we are using the `\""` syntax which allows us to [use a capitalized identifier name](./use-illegal-identifier-names).

<CodeTab labels={["ReScript", "JS Output"]}>

```res example
type audioContext

@new external createAudioContext: unit => audioContext = "AudioContext"

let createAudioContext: unit => option<audioContext> = () => {
switch %external(\"AudioContext") {
| Some(_) => createAudioContext()->Some
| None => None
}
}
```

```js
var Caml_option = require("rescript/lib/js/caml_option.js");

function createAudioContext(param) {
var match = typeof AudioContext === "undefined" ? undefined : AudioContext;
if (match !== undefined) {
return Caml_option.some(new AudioContext());
}
}
```

</CodeTab>

<!-- TODO: revamp this page. Not good. Tell to use globalThis["foo"], and look in our stdlib -->