使用 RxJS 的 scan 操作符时,如何借助 TypeScript 模板字面量类型保证 action 类型收窄?

解读

在国内一线/二线大厂的 Angular 面试中,**“状态管理 + 类型安全”**是高频考点。
面试官真正想验证的是:

  1. 你是否把 Redux 风格的状态机(NgRx、ComponentStore、Akita 均可)与 RxJS 原生能力结合,而不是只会用现成库;
  2. 你是否能用 TypeScript 4.1+ 模板字面量类型 把“字符串字面量 + 联合类型”玩出花,实现 “一个 reducer 文件零类型断言” 的极致类型收窄;
  3. 你是否理解 scan 的“累加器”本质,并能把类型流同步到累加器函数体内,让 switch case 的每个分支自动推断 payload 类型,杜绝 any 或 as 的“中国式兜底”写法。

知识点

  • scan 操作符:RxJS 的“reduce + 状态机”,每次上游发射都会回调 (acc, val) => nextAcc,必须保证 acc 与 val 的类型契约;
  • 模板字面量类型:${Domain}/${Event} 模式,可把无穷散列字符串压缩成有限联合类型,在编译期完成“命名空间隔离”;
  • discriminated union(可辨识联合):借助唯一字面量字段(type 或 event)让 TypeScript 自动收窄;
  • const assertion + satisfies:保证定义 action creator 时不丢失字面量类型,避免“string 泛化”;
  • strictNullChecks & strictFunctionTypes:国内项目常因老代码关闭严格模式,面试时需主动强调“必须全开严格模式,否则字面量类型会回退”。

答案

  1. 定义域前缀与事件名,利用模板字面量一次性生成全部 action type 联合
// 1. 域隔离,防止团队并行开发冲突
export type TodoDomain = 'todo';

// 2. 事件池
export type TodoEvent = 'add' | 'toggle' | 'remove';

// 3. 编译期生成 `${domain}/${event}` 联合,共 3 种可能
export type TodoActionType = `${TodoDomain}/${TodoEvent}`;
  1. 用工厂函数生成 discriminated union,payload 类型与 type 字符串强绑定
export type TodoAction<T extends TodoEvent> = {
  type: `${TodoDomain}/${T}`;
  payload: T extends 'add'
    ? { title: string }
    : T extends 'toggle'
    ? { id: number }
    : { id: number };
};

// 利用“函数重载 + 泛型”一次性生成三个 action creator,返回类型自动收窄
export function createTodoAction<T extends TodoEvent>(
  event: T,
  payload: TodoAction<T>['payload']
): TodoAction<T> {
  return { type: `todo/${event}`, payload } as TodoAction<T>;
}
  1. 在 scan 累加器内部,switch 语句直接享受类型收窄
type State = { list: Array<{ id: number; title: string; done: boolean }> };

const initial: State = { list: [] };

export const todoReducer = (state: State = initial, action: TodoAction<TodoEvent>): State => {
  switch (action.type) {
    case 'todo/add': {
      // 自动推断 payload 为 { title: string }
      const { title } = action.payload;
      return {
        list: [...state.list, { id: Date.now(), title, done: false }],
      };
    }
    case 'todo/toggle': {
      // 自动推断 payload 为 { id: number }
      const { id } = action.payload;
      return {
        list: state.list.map((it) =>
          it.id === id ? { ...it, done: !it.done } : it
        ),
      };
    }
    case 'todo/remove': {
      const { id } = action.payload;
      return { list: state.list.filter((it) => it.id !== id) };
    }
    default: {
      // 利用“never 检查”保证穷尽性
      const _: never = action;
      return state;
    }
  }
};
  1. 在组件或服务里用 scan 做本地轻量级状态机,全程零类型断言
actions$ = new Subject<TodoAction<TodoEvent>>();

state$ = this.actions$.pipe(
  scan(todoReducer, initial),
  shareReplay({ bufferSize: 1, refCount: true })
);

// 调用端
this.actions$.next(createTodoAction('add', { title: '学习模板字面量' }));

至此,scan 的累加器函数内部每一个 case 分支都享受到 TypeScript 的精确类型收窄,编译器会拒绝任何错误 payload 形状,实现“写错即爆红,运行零异常”的国内大厂代码审查标准。

拓展思考

  • “域前缀 + 模板字面量” 不仅适用于 todo,也可推广到 feature 模块级别,如 ${module}/${subFeature}/${event},在微前端场景下天然隔离团队命名空间;
  • 若项目已用 NgRx,可用同样的模板字面量生成 Action 类型,替代官方 createAction 的 props 泛型,在大型 monorepo 中减少重复代码 30% 以上;
  • 对于高频异步场景,可把 scan 与 switchMap + catchError 组合,实现“乐观更新 + 失败回滚”的局部事务机制,此时模板字面量类型依旧保证回滚 action 的 payload 不被篡改;
  • 面试加分项:主动提及“模板字面量类型在编译期被完全擦除,运行时仍是普通字符串,对包体积零影响”,可打消面试官对“类型体操导致 bundle 增大”的顾虑。