Reason: Object property type not being enforced

Created on 29 Mar 2018  路  3Comments  路  Source: reasonml/reason

type person = {
    name: string,
    age: int
};

let person = {
    "John"
};

person of type string is being allowed despite being typed as an object, why is that ?

Most helpful comment

@hcarty beat me to it, but one bonus thing to note is that you often won't need to use these sort of annotations once you start actually using the variable. You can see that the compiler will infer the type of person and throw an error if you try to access one of the record's fields:

let foo = person.name;  >> Line 5, 10: This expression has type string but an expression was expected of type person

So you know the typechecker's got your back even when you're not annotating your variables 馃槃

All 3 comments

The type person does not get applied/inferred automatically to a value named person. If you want, you can apply a type annotation to the person definition which will give the type error you're looking for:
```
type person = {
name: string,
age: int
};

/* This will result in a type error */
let person : person = {
"John"
};

@hcarty beat me to it, but one bonus thing to note is that you often won't need to use these sort of annotations once you start actually using the variable. You can see that the compiler will infer the type of person and throw an error if you try to access one of the record's fields:

let foo = person.name;  >> Line 5, 10: This expression has type string but an expression was expected of type person

So you know the typechecker's got your back even when you're not annotating your variables 馃槃

@hcarty Thanks for explaining that, I assumed wrong that if variable_name and variable_type are same it is assumed to be of its type.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

modlfo picture modlfo  路  4Comments

jberdine picture jberdine  路  3Comments

braibant picture braibant  路  4Comments

gustavopinto picture gustavopinto  路  3Comments

rickyvetter picture rickyvetter  路  3Comments