JeromeBu
JeromeBu

Reputation: 1159

How to use a variant option to type function parameters in rescript?

I would like to do the following. But it seems I cannot type the function parameter with one of the variant option. What would be the proper way to achieve this in rescript? 

Here is a playground

  type subject = Math | History

  type person =
    | Teacher({firstName: string, subject: subject})
    | Student({firstName: string})
  
  let hasSameNameThanTeacher = (
    ~teacher: Teacher, // syntax error here
    ~student: Person,
  ) => {
    teacher.firstName == student.firstName
  }

Upvotes: 0

Views: 256

Answers (1)

glennsl
glennsl

Reputation: 29126

Teacher and Student are not types themselves, but constructors that construct values of type person. If you want them to have distinct types you have to make it explicit:

module University = {
  type subject = Math | History

  type teacher = {firstName: string, subject: subject}
  type student = {firstName: string}
  type person =
    | Teacher(teacher)
    | Student(student)
  
  let hasSameNameThanTeacher = (
    ~teacher: teacher,
    ~student: student,
  ) => {
    teacher.firstName == student.firstName
  }
}

Upvotes: 1

Related Questions