示例工程 08-unions-intersections

08-unions-intersections/01-union-basics/src/main.ts

typescript · 0.7 KB

运行:08 · union-basics

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

// 演示:联合类型只共享公共操作,具体类型要靠收窄
export type Id = string | number;
 
export type Maybe<T> = T | null;
 
export function toKey(id: Id): string {
  return typeof id === 'string' ? id : id.toString();
}
 
export function firstId(ids: readonly Id[]): Id | undefined {
  return ids[0];
}
 
export function orDefault(value: Maybe<string>): string {
  return value ?? '(none)';
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines = [
    toKey('abc'),
    toKey(42),
    String(firstId([7, 'x'])),
    orDefault(null),
    orDefault('ok'),
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}