示例工程 03-literal-types-narrowing

03-literal-types-narrowing/01-literal-widening/src/main.ts

typescript · 0.6 KB

运行:03 · literal-widening

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

// 演示:字面量类型会被拓宽,标注与 as const 可以阻止拓宽
export type Direction = 'up' | 'down' | 'left' | 'right';
 
export const literal = 'up';
export let widened = 'up';
export const fixed = 'up' as const;
export let current: Direction = 'up';
 
export function turn(next: Direction): string {
  current = next;
  return current;
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  widened = 'left';
  const lines = [
    `literal=${literal}`,
    `widened=${widened}`,
    `fixed=${fixed}`,
    `turn=${turn('down')}`,
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}