示例工程 03-literal-types-narrowing

03-literal-types-narrowing/03-in-narrowing/src/main.ts

typescript · 0.5 KB

运行:03 · in-narrowing

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

// 演示:用 in 操作符收窄对象联合
export type ApiResponse =
  | { data: string[] }
  | { error: string };
 
export function unwrap(response: ApiResponse): string {
  if ('error' in response) {
    return `error:${response.error}`;
  }
  return `ok:${response.data.join(',')}`;
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines = [
    unwrap({ data: ['a', 'b'] }),
    unwrap({ error: 'not found' }),
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}