【问题标题】:How to use a variant option to type function parameters in rescript?如何使用变体选项在脚本中键入函数参数?
【发布时间】:2021-04-14 08:56:48
【问题描述】:

我想做以下事情。但似乎我无法使用变体选项之一键入函数参数。在脚本中实现这一目标的正确方法是什么?

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
  }

【问题讨论】:

    标签: types variant rescript


    【解决方案1】:

    TeacherStudent 本身不是类型,而是构造 person 类型值的构造函数。如果您希望它们具有不同的类型,则必须明确说明:

    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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 2020-03-16
      • 2015-07-27
      • 1970-01-01
      • 2013-04-25
      • 2019-07-03
      相关资源
      最近更新 更多