← 中文资源

简体中文版本

类型安全的有限状态机

用状态与事件的字面量联合和转移表实现泛型状态机,非法事件抛出带状态信息的错误,并记录访问过的每个状态。

阅读英文原文

题目

实现泛型 StateMachine<S, E>,构造参数包括初始状态和转移表,转移表类型为 Record<S, Partial<Record<E, S>>>。机器要记录初始状态,state 返回当前状态,send(event) 在合法时迁移并返回新状态,非法时抛出 INVALID:EVENT:STATE。示例驱动一个请求生命周期(idle、loading、success、error),输出 states 数组和 error(无错误时为 null)。

解题思路

States 与 Events 都声明为字面量联合,转移表用 Record<States, Partial<Record<Events, States>>> 描述:每个状态都必须出现,但每个状态只需列出合法事件。send 先取 this.table[this.current][event],得到 undefined 说明该事件在当前状态不可用,立即抛出包含事件名和当前状态的错误;否则更新 current 并返回。主流程先把初始状态放入数组,再逐个处理事件,遇到异常记录 message 并停止。

参考实现要点

转移表的值可能是 undefined,因此判断用 if (!next) 或显式判空都可以,但不能把空字符串当成合法状态。Record<States, …> 强制为每个状态提供配置,新增状态却忘记加入转移表时编译器会报错。state 用 getter 暴露只读值,外部无法直接修改 current。错误消息格式固定为 INVALID:事件:状态,便于与 expected 逐字比较。

常见错误

遇到未知事件直接返回当前状态,调用方会以为事件已被处理,状态却悄悄停住。把转移表类型写成 Record<string, Record<string, string>>,拼错状态名或事件名时编译器不报错。忘记把初始状态放进 states,输出会缺少第一项。出错后继续处理后续事件,可能进入一个本不该出现的状态。

验证方式

用 tsc –strict 编译,确认 States 新增成员后转移表必须同步补齐,否则报错。运行三个样例并比对 JSON。补充测试:loading 状态下发送 RESET 应产生 INVALID:RESET:loading;成功路径的 error 必须为 null;states 的第一项始终等于 initial。最后确认抛出错误后不再处理剩余事件。

代码示例

declare const input: string;

type States = 'idle' | 'loading' | 'success' | 'error';
type Events = 'FETCH' | 'SUCCESS' | 'FAIL' | 'RESET';

const transitions: Record<States, Partial<Record<Events, States>>> = {
  idle: { FETCH: 'loading' },
  loading: { SUCCESS: 'success', FAIL: 'error' },
  success: { RESET: 'idle', FETCH: 'loading' },
  error: { RESET: 'idle', FETCH: 'loading' },
};

class StateMachine<S extends string, E extends string> {
  constructor(
    private current: S,
    private readonly table: Record<S, Partial<Record<E, S>>>,
  ) {}

  get state(): S {
    return this.current;
  }

  send(event: E): S {
    const next = this.table[this.current][event];
    if (!next) throw new Error(`INVALID:${event}:${this.current}`);
    this.current = next;
    return next;
  }
}

interface Spec {
  initial: States;
  events: Events[];
}

const spec = JSON.parse(input) as Spec;
const machine = new StateMachine<States, Events>(spec.initial, transitions);
const states: States[] = [machine.state];
let error: string | null = null;

for (const event of spec.events) {
  try {
    states.push(machine.send(event));
  } catch (caught) {
    error = caught instanceof Error ? caught.message : String(caught);
    break;
  }
}

console.log(JSON.stringify({ states, error }));