Function Overloads for a Parser

Declare overload signatures so one parser returns a typed object for structured input and a string for plain input, guiding callers precisely.

TypescriptData Integrity

Code

typescriptsnippet
18 lines
export interface ParseOptions {
  contentType: "application/json";
}

export function parse(input: string, options: ParseOptions): Record<string, unknown>;
export function parse(input: string, options?: { contentType?: "text/plain" }): string;
export function parse(
  input: string,
  options?: ParseOptions | { contentType?: "text/plain" },
): string | Record<string, unknown> {
  if (options && options.contentType === "application/json") {
    return JSON.parse(input) as Record<string, unknown>;
  }
  return input.trim();
}

const text = parse("  hello  ");
const record = parse("{\"a\":1}", { contentType: "application/json" });

How the snippet works

Function Overloads for a Parser is built around the function parse.

What to watch for

  • The guard options && options.contentType === "application/json" short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads export function parse(input: string, options: ParseOptions)

Import parse from the file and call it — the rest of the code is implementation detail.

Statements that matter

return JSON.parse(input) as Record<string, unknown>;
return input.trim();

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `parse` at load time.