处理 JavaScript 中的可选 return 值的最佳方法是什么?
What is the best way to handle optional return values in JavaScript?
我正在尝试在 JavaScript 中编写一个函数,return 要么是一个值,要么是 false。有没有像 Scala 中那样的 'option' return 类型?例如,在 Scala 中:
def foo(): Option[T]()
在 JavaScript 中,我能找到的唯一方法是通过不同的 return 值:
function foo() {
if (x) {
return "value";
} else {
return false;
}
}
这是惯用的还是有更好的方法?
不,没有。考虑 JS 是 "weakly typed".
在这种情况下,通常您是 return null
或 undefined
。
对于 returns 对象类型的函数,通常是第一个,例如在 DOM API:
let node = document.getElementById("foo");
if (node) {
// do something
}
如果不存在 ID 为 foo
的节点,则 node
将为 null
。检查有效,因为 null
是一个 falsy
值。
在你的例子中,如果你 return 一个字符串,最好的可能是 return 一个空字符串——也就是 "falsy"——或者 undefined
.
但没有什么比 Option
是 Scala 或 Rust。
Javascript 不附带标记的联合。但是,您可以轻松地自己实现它们:
const union = type => (tag, o) =>
(o[type] = type, o.tag = tag.name || tag, o);
const match = (tx, o) =>
o[tx.tag] (tx);
const Option = union("Option");
const None = Option("None", {});
const Some = some => Option(Some, {some});
const head = xs =>
xs.length === 0
? None
: Some(xs[0]);
const xs = [11,22,33],
ys = [];
const foo = match(head(xs), {
None: () => 0,
Some: ({some}) => some
});
const bar = match(head(ys), {
None: () => 0,
Some: ({some}) => some
});
console.log(foo, bar);
请注意 Some
/None
创建的 Option
类型包含一个奇怪的 Option: "Option"
属性。这样做的好处是每个标记的联合类型在结构上都是唯一的,这简化了它们在 Typescript 中的使用。
我正在尝试在 JavaScript 中编写一个函数,return 要么是一个值,要么是 false。有没有像 Scala 中那样的 'option' return 类型?例如,在 Scala 中:
def foo(): Option[T]()
在 JavaScript 中,我能找到的唯一方法是通过不同的 return 值:
function foo() {
if (x) {
return "value";
} else {
return false;
}
}
这是惯用的还是有更好的方法?
不,没有。考虑 JS 是 "weakly typed".
在这种情况下,通常您是 return null
或 undefined
。
对于 returns 对象类型的函数,通常是第一个,例如在 DOM API:
let node = document.getElementById("foo");
if (node) {
// do something
}
如果不存在 ID 为 foo
的节点,则 node
将为 null
。检查有效,因为 null
是一个 falsy
值。
在你的例子中,如果你 return 一个字符串,最好的可能是 return 一个空字符串——也就是 "falsy"——或者 undefined
.
但没有什么比 Option
是 Scala 或 Rust。
Javascript 不附带标记的联合。但是,您可以轻松地自己实现它们:
const union = type => (tag, o) =>
(o[type] = type, o.tag = tag.name || tag, o);
const match = (tx, o) =>
o[tx.tag] (tx);
const Option = union("Option");
const None = Option("None", {});
const Some = some => Option(Some, {some});
const head = xs =>
xs.length === 0
? None
: Some(xs[0]);
const xs = [11,22,33],
ys = [];
const foo = match(head(xs), {
None: () => 0,
Some: ({some}) => some
});
const bar = match(head(ys), {
None: () => 0,
Some: ({some}) => some
});
console.log(foo, bar);
请注意 Some
/None
创建的 Option
类型包含一个奇怪的 Option: "Option"
属性。这样做的好处是每个标记的联合类型在结构上都是唯一的,这简化了它们在 Typescript 中的使用。