Narrow Split Strings Into Fixed Tuples

Refine string[] output from String.prototype.split into a fixed-length tuple using a custom type guard so positional destructuring stays strictly typed.

TypescriptCli Tooling

Code

typescriptsnippet
23 lines
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)));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Implementation flow — Narrow Split Strings Into Fixed Tuples

Under the hood: the functions isTriple and parseEndpoint.

Iteration happens inside for (const raw of ['api.internal:8443:prod', 'localhost:80', 'bad:port:dev']) — everything outside it runs once.

The result comes back as an object carrying host, port.

Caveats

  • Nothing arrives from a registry; the language ships every API used.

Using it

The entry-point signature is function isTriple(parts: readonly string[])

The call returns host, port — destructure what you need at the call site.

Key statements

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

Interactive Tools for This Topic

FAQ

Does `isTriple` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `isTriple`, `parseEndpoint` at load time.