首页 > 解决方案 > 如何细化采用数组联合的函数中的类型?

问题描述

根据输入数组的类型,有一些函数将工作委托给其他函数。我如何指出特定数组必须由特定函数处理?

我一直在考虑它并搜索了几个小时,但找不到解决方案。

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);
  }
}

flow.org/try 上的代码

标签: javascriptarraysflowtype

解决方案


无法根据数组中项目的类型进行细化。

这是因为数组访问是不安全的——数组访问总是有可能返回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)
  }
}

这是尝试流程链接

不幸的 :(


推荐阅读