elm中如何在其他地方使用一条记录的字段类型
How do I use the field type of a record in other places in elm
考虑一下:
type alias Foo =
{ id : String
, name : String
}
type alias Bar =
{ id : Foo.id
, name : String
}
据我所知,这在 elm 中不起作用。 (我的意思是使用“Foo.id”)。
我可以将 Bar 中的 id 字段设置为 String,但我希望它使用另一条记录的 id 类型。所以 when/if 我以后需要重构它,我只能在一个地方做。
这是我尝试执行此操作时看到的错误消息 *
The type expected 0 arguments, but got 1 instead
额外上下文:总体而言,我对 Elm 语言和函数式编程还比较陌生。我有相当多的 Typescript 经验。所以我习惯于创建定义明确的类型。不确定在 Elm 中是否是这样做的。所以我来这里是为了学习和发现。
如果你倾向于去重id
字段的类型,你可以考虑将其提取到自己的类型中:
type alias Id = String
type alias Foo =
{ id : Id
, name : String
}
type alias Bar =
{ id : Id
, name : String
}
你可以这样做。它会将字符串包装在 Id
中并添加一个类型来帮助您强制正确使用:
type UserId = UserId -- we have a type called "UserId" who's only value is "UserId"
type ProjectId = ProjectId -- ...
type Id a = Id String -- an Id has a specific type "a" and is always a wrapper for a string
userId : String -> Id UserId
user = Id -- Id is always a constructor, but the type signature forces Elm to treat this as a "Id UserId". Only code that expects an "Id UserId" can accept this
projectId : String -> Id ProjectId
project = Id
-- any Id can be turned back into a string
toString : Id a -> String
toString (Id a) = a
考虑一下:
type alias Foo =
{ id : String
, name : String
}
type alias Bar =
{ id : Foo.id
, name : String
}
据我所知,这在 elm 中不起作用。 (我的意思是使用“Foo.id”)。
我可以将 Bar 中的 id 字段设置为 String,但我希望它使用另一条记录的 id 类型。所以 when/if 我以后需要重构它,我只能在一个地方做。 这是我尝试执行此操作时看到的错误消息 *
The type expected 0 arguments, but got 1 instead
额外上下文:总体而言,我对 Elm 语言和函数式编程还比较陌生。我有相当多的 Typescript 经验。所以我习惯于创建定义明确的类型。不确定在 Elm 中是否是这样做的。所以我来这里是为了学习和发现。
如果你倾向于去重id
字段的类型,你可以考虑将其提取到自己的类型中:
type alias Id = String
type alias Foo =
{ id : Id
, name : String
}
type alias Bar =
{ id : Id
, name : String
}
你可以这样做。它会将字符串包装在 Id
中并添加一个类型来帮助您强制正确使用:
type UserId = UserId -- we have a type called "UserId" who's only value is "UserId"
type ProjectId = ProjectId -- ...
type Id a = Id String -- an Id has a specific type "a" and is always a wrapper for a string
userId : String -> Id UserId
user = Id -- Id is always a constructor, but the type signature forces Elm to treat this as a "Id UserId". Only code that expects an "Id UserId" can accept this
projectId : String -> Id ProjectId
project = Id
-- any Id can be turned back into a string
toString : Id a -> String
toString (Id a) = a