Namespace Merging Attaches Static Members

Merge a namespace with a function or class to attach constants and factory helpers, keeping one name for related runtime values.

TypescriptData Integrity

Code

typescriptsnippet
34 lines
function format(value: number, unit: string): string {
  return value.toFixed(2) + unit;
}

// Namespace merging: 给函数挂上静态成员
namespace format {
  export const percent = (value: number): string => value.toFixed(1) + '%';

  export function padded(value: number, width: number): string {
    return value.toString().padStart(width, '0');
  }
}

console.log(format(3.14159, 'px'));
console.log(format.percent(42.123));
console.log(format.padded(7, 3));

// namespace 也能与 class 合并
class Parser {
  parse(raw: string): number {
    return Number.parseInt(raw, 10);
  }
}

namespace Parser {
  export const version = '1.0';

  export function create(): Parser {
    return new Parser();
  }
}

const parser = Parser.create();
console.log('parsed:', parser.parse('2048'), '| version:', Parser.version);

Inside the snippet

Namespace Merging Attaches Static Members keeps everything in the class Parser and the functions percent, format, padded and create.

The result is a fresh construction, so callers can keep their originals.

Using it

Entry signature: export const percent = (value: number)

The demo output is labeled (parsed:), so every line of output points back to the operation that emitted it.

The surface worth importing is percent; the helpers around it are private to the snippet.

Key statements

export const percent = (value: number): string => value.toFixed(1) + '%';
return value.toString().padStart(width, '0');
return Number.parseInt(raw, 10);

Interactive Tools for This Topic

FAQ

Does `percent` modify its input?
No mutation happens — the function reads its input and returns a new value.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `percent`, `format`, `padded` at load time.