在像 OCaml 这样的函数式语言中,我们有模式匹配。例如,我想记录用户在我的网站上的操作。操作可以是 1) 访问网页,2) 删除项目,3) 检查其他用户的个人资料等。在 OCaml 中,我们可以编写如下内容:
type Action =
| VisitPage of string (* www.myweb.com/help *)
| DeletePost of int (* an integer post id *)
| ViewUser of string (* a username *)
但是,我不确定如何定义这个Action
在 JavaScript 中。我能想到的一种方法是
var action_1 = { pageVisited: "www.myweb.com/help", postDeleted: null, userViewed: null }
var action_2 = { pageVisited: null, postDeleted: 12345, userViewed: null }
var action_3 = { pageVisited: null, postDeleted: null, userViewed: "SoftTimur" }
但这个结构并没有表达出pageVisited
, postDeleted
and userViewed
其中是独一无二的。
有人能提出在 JavaScript 中更好地表示这种类型吗?
在 JavaScript 或 TypeScript 中是否存在进行模式匹配的通用方法?