类型不匹配对于自定义类型

问题描述

我认为代码比我用普通英语解释更能说明问题。

这是领域建模的代码

module Domain.A exposing (..)

import Domain.B

type Size
  = Pound Float
  | Kilogram Float
  | Gram Float
  | Liter Float
  | Ounce Float
  | Count Int

type StockStatus 
  = InStock
  | OutOfStock

type alias CityWholesalerProduct =
  {
    cityWholesalerId : String,brand : String,productSku : Maybe String,sku : String,upc : Maybe String,description : String,status : StockStatus,price : Float,unit : Domain.B.Unit,pack : Int,size : Size
  }

这是 Main.elm 中模型的代码

-- MODEL

type alias Model =
  { cityWholesalerProducts : (List Domain.A.CityWholesalerProduct),cityWholesalerProduct : Domain.A.CityWholesalerProduct
  }

init : Model
init = 
  Model 
    [] 
    {
      cityWholesalerId = "",brand = "",productSku = "",sku = "",upc = "",description = "",status = Domain.A.OutOfStock,price = 0.00,unit = Domain.B.Count,pack = 0,size = Domain.A.Count 0
    }

问题是我收到一条错误消息:

TYPE MISMATCH - The 2nd argument to `Model` is not what I expect:

34|   Model 
35|     [] 
36|#>#    {
37|#>#      cityWholesalerId = "",38|#>#      brand = "",39|#>#      productSku = "",40|#>#      sku = "",41|#>#      upc = "",42|#>#      description = "",43|#>#      status = Domain.A.OutOfStock,44|#>#      price = 0.00,45|#>#      unit = Domain.B.Count,46|#>#      pack = 0,47|#>#      size = Domain.A.Count 0
48|#>#    }

This argument is a record of type:

    { brand : String,cityWholesalerId : String,productSku : #String#,size : Domain.A.Size,status : Domain.A.StockStatus,upc : #String#
    }

But `Model` needs the 2nd argument to be:

    #Domain.A.CityWholesalerProduct#

#Hint#: I always figure out the argument types from left to right. If an argument
is acceptable,I assume it is “correct” and move on. So the problem may actually
be in one of the prevIoUs arguments!

一般来说,我是 Elm 和 FP 的新手,类型不匹配错误是我最大的痛点,我已经坚持了一段时间了。

解决方法

我很惊讶 Elm 编译器 - 通常会提供非常有用的错误消息 - 在这里没有更具体。但是我看到的问题只是在这些字段中 - productSkuupc - 你的类型别名说它们应该是 Maybe String 类型,但是你已经用值 {{1} },它只是一个 ""

不清楚哪个部分是错误的。如果这些总是应该是简单的字符串,那么修复类型声明,在这些地方将 String 更改为 Maybe String。但我认为类型声明可能如您所愿,并且值是错误的。你可以试试这个:

String

至少应该编译 - 但我无法评论您预期的业务逻辑的正确值是什么。我不清楚 init = Model [] { cityWholesalerId = "",brand = "",productSku = Just "",sku = "",upc = Just "",description = "",status = Domain.A.OutOfStock,price = 0.00,unit = Domain.B.Count,pack = 0,size = Domain.A.Count 0 } 对这些 Nothing 值意味着什么,以及这与 Maybe 是否真的有任何不同 - 但它们很可能是。