Skip to content
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

Syntax lookup: Type coercion operator #435

Merged
merged 1 commit into from
Sep 3, 2021
Merged
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
69 changes: 69 additions & 0 deletions misc_docs/syntax/operators_type_coercion.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
id: "type-coercion"
keywords: ["operator", "type", "coercion", "polymorphic", "variant", "polyvar", "object"]
name: ":>"
summary: "This is the `type coercion` operator."
category: "operators"
---

The `:>` operator may be used to convert a polymorphic variant to a `string` or `int`, or convert an [object](/docs/manual/latest/object) to a type with a subset of its fields.

### Example 1

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

```res
type color = [#Red | #Green | #Blue]
let color: color = #Red
let message = "The color is " ++ (color :> string)
```

```js
var message = "The color is Red";
```

</CodeTab>

### Example 2

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

```res
type bit = [#0 | #1]
let bit: bit = #1
let value = (bit :> int)
```

```js
var bit = 1;
var value = 1;
```

</CodeTab>

### Example 3

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

```res
type person = {"id": int, "name": string}
type name = {"name": string}
let person = {"id": 10, "name": "Gideon"}
let name = (person :> name)
```

```js
var person = {
id: 10,
name: "Gideon",
};

var name = person;
```

</CodeTab>


### References

* [Polymorphic Variant Coercion](/docs/manual/latest/polymorphic-variant#coercion)