← 中文资源

简体中文版本

用类型守卫把 split 数组收窄为定长元组

String.prototype.split 只返回宽泛的 string[];借助长度校验型类型守卫把它收窄成固定元组,让位置解构保留精确元素类型。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

api.internal:8443:prod -> {"host":"api.internal","port":8443,"env":"prod"}
localhost:80 -> null
bad:port:dev -> null

实现说明

用类型守卫把 split 数组收窄为定长元组可以归结为函数 isTriple、parseEndpoint。 迭代发生在 for (const raw of ['api.internal:8443:prod', 'localhost:80', 'bad:port:dev']) 内部——循环之外的语句只执行一遍。 返回值是携带 host、port 的对象。

使用要点

  • 工具链本身就够——不发生任何依赖解析。

常见问题

isTriple 会修改传入的参数吗?

不会。传入的任何东西都不会被写入,对共享数据调用是安全的。

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 isTriple、parseEndpoint。

签名一览:function isTriple(parts: readonly string[])

核心语句

return parts.length === 3 && parts.every((part) => part.length > 0);
return { host, port, env };

代码示例

type EndpointTriple = [host: string, portRaw: string, env: string];

function isTriple(parts: readonly string[]): parts is EndpointTriple {
  return parts.length === 3 && parts.every((part) => part.length > 0);
}

function parseEndpoint(line: string): { host: string; port: number; env: string } | null {
  const parts = line.trim().split(':');
  if (!isTriple(parts)) {
    return null;
  }
  // `parts` is now narrowed from `string[]` to `[string, string, string]`
  const [host, portRaw, env] = parts;
  const port = Number(portRaw);
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    return null;
  }
  return { host, port, env };
}

for (const raw of ['api.internal:8443:prod', 'localhost:80', 'bad:port:dev']) {
  console.log(raw, '->', JSON.stringify(parseEndpoint(raw)));
}