首页 > 解决方案 > 返回“响应”对象或元组的模式的名称

问题描述

在编写 JavaScript/TypeScript 时,我有时会实现一种模式,其中函数返回响应对象(如下所示)或响应“元组”(仅表示包含两个项目的数组),而不是原始值。像这样的东西:

example.js

function getName() {
  if (userPressedOk) {
    return {status: "OK", name: getName()}
  else {
    return {status: "FAIL", name: ""}
  }
}

example.ts

function getName(): { status: string; jobName: string } {
  if (userPressedOk) {
    return {status: "OK", name: getName()}
  else {
    return {status: "FAIL", name: ""}
  }
}

这是一个稍微做作的例子,但这是基本思想。我试图模仿我在函数式编程语言中看到的风格。这种模式有名字吗?

标签: javascripttypescriptfunctional-programming

解决方案


我见过它们称为Result Objects

在您说要借用的功能语言中,通常调用相应的类型ResultEither(尽管它通常在失败情况下提供错误消息,而不是默认值)。


推荐阅读