I am pretty new to rescript and trying to understand how things are working. In my situation I would like to access a key from a variant type like this.
type personType = Person({name: string, age: int})
let person = Person({
name: "Jane",
age: 35,
})
Js.log(person.name) // -> Error: The record field name can't be found.
The following, using a record, is working:
type personRecord = {
name: string,
age: int,
}
let personAsRecord = {name: "Bob", age: 30}
Js.log(personAsRecord.name)
Another option would be to use pattern matching, which also works :
let personName = switch person {
| Person({name}) => name
}
Js.log(personName)
So my question is : is this because the type is a variant and the typing is not structural type unlike typescript ? Is the only way to access a variant keys to use pattern matching ?
Is the only way to access a variant keys is to use pattern matching ?
Yes.
Although you can also deconstruct/pattern match in a let
binding:
let Person({name}) = person
and function argument:
let print = (Person({name})) => Js.log(name)
is this because the type is a variant and the typing is not structural type unlike typescript ?
I don't really see what structural typing would have to do with it. A variant can have, and typically has, multiple "cases" with different payloads, and you can't safely access their properties if you don't know that they're actually there. Therefore you have to pattern match to determine which case it is, and then you can access its properties.