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.
Code
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 -> nullImplementation 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.