示例工程 03-literal-types-narrowing

03-literal-types-narrowing/05-assertion-functions/src/main.ts

typescript · 1.0 KB

运行:03 · assertion-functions

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 演示:断言函数在返回后永久收窄;失败时抛异常
export function assertIsString(value: unknown, label: string): asserts value is string {
  if (typeof value !== 'string') {
    throw new TypeError(`${label} must be a string`);
  }
}
 
export function assertDefined<T>(value: T, label: string): asserts value is NonNullable<T> {
  if (value === null || value === undefined) {
    throw new TypeError(`${label} must be defined`);
  }
}
 
export function normalize(value: unknown): string {
  assertIsString(value, 'value');
  return value.trim().toLowerCase();
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines = [normalize('  TS  ')];
  try {
    normalize(42);
  } catch (error) {
    const name = error instanceof Error ? error.constructor.name : 'unknown';
    lines.push(`threw:${name}`);
  }
  let optional: string | undefined = 'ok';
  assertDefined(optional, 'optional');
  lines.push(optional);
  for (const line of lines) {
    log(line);
  }
  return lines;
}