示例工程 03-literal-types-narrowing

03-literal-types-narrowing/04-type-predicates/src/main.ts

typescript · 0.7 KB

运行:03 · type-predicates

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

// 演示:类型谓词把 unknown 收窄成具体结构
export interface User {
  id: number;
  name: string;
}
 
export function isUser(value: unknown): value is User {
  if (typeof value !== 'object' || value === null) return false;
  const record = value as Record<string, unknown>;
  return typeof record['id'] === 'number' && typeof record['name'] === 'string';
}
 
export function names(values: unknown[]): string[] {
  return values.filter(isUser).map((user) => user.name);
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines = names([
    { id: 1, name: 'Ada' },
    { id: '2', name: 'broken' },
    null,
    { id: 3, name: 'Linus' },
  ]);
  for (const line of lines) {
    log(line);
  }
  return lines;
}