javascript - 如何细化采用数组联合的函数中的类型?
问题描述
根据输入数组的类型,有一些函数将工作委托给其他函数。我如何指出特定数组必须由特定函数处理?
我一直在考虑它并搜索了几个小时,但找不到解决方案。
type nameType = {
name: string,
}
type surnameType = {
surname: string
};
type inputType = nameType[] | surnameType[];
function processSurnames(suranmes: surnameType[]) {
let result = {};
// do something with surnames
return result;
}
function processNames(names: nameType[]) {
let result = {};
// do something with names
return result;
}
function process(input: inputType) {
if (typeof input[0].name === 'string') { // <--- this refinement doesn't work
return processNames(input);
} else {
return processSurnames(input);
}
}
解决方案
无法根据数组中项目的类型进行细化。
这是因为数组访问是不安全的——数组访问总是有可能返回undefined
。可以用数组以外的任何东西进行细化。
我已经重写了您的示例,将数组包装在对象中并基于“类型”属性进行了改进。
// ...
type Names = { type: "names", list: nameType[] }
type Surnames = { type: "surnames", list: surnameType[] }
// ...
export function process(input: Names | Surnames) {
if (input.type === "names") {
return processNames(input.list)
} else {
return processSurnames(input.list)
}
}
不幸的 :(
推荐阅读
- javascript - Flow Builder(可视化编辑器)
- php - 无效参数:查询中未定义令牌帐户
- flask - WTForms booleanfield 总是返回 True
- android - 应用程序处于打盹模式时显示警报通知?
- sql - SQL:如何将值从一个键复制到另一个键
- reactjs - 使用 react-app-rewired 和 customize-cra 时如何配置 Jest?
- c# - 如何对 JObject 数组进行排序?
- c# - 如何使用gridview将每个变量放在单独的列中
- javascript - 如何以非阻塞方式组合可观察对象?
- ssl - 使用 vertx 在服务器和客户端之间建立 SSL 连接