示例工程 03-literal-types-narrowing

03-literal-types-narrowing/02-typeof-narrowing/src/main.ts

typescript · 0.5 KB

运行:03 · typeof-narrowing

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

// 演示:typeof 收窄联合类型
export type Input = string | string[] | null;
 
export function firstValue(input: Input): string {
  if (input === null) return '(null)';
  if (typeof input === 'string') return input;
  return input[0] ?? '(empty)';
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines = [
    firstValue('ts'),
    firstValue(['a', 'b']),
    firstValue([]),
    firstValue(null),
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}