// 定义状态类型
type State = 'initial' | 'processing' | 'completed' |'rejected';
// 定义状态转换函数类型
type TransitionFunction = (currentState: State) => boolean;
// 定义状态转换规则
const transitions: { [key in State]: TransitionFunction[] } = {
initial: [(state) => state === 'processing'],
processing: [(state) => state === 'completed' || state ==='rejected'],
completed: [],
rejected: []
};
// 类型保护函数
function canTransition(currentState: State, nextState: State): boolean {
return transitions[currentState].some(transition => transition(nextState));
}
// 示例代码
let currentState: State = 'initial';
// 尝试从 initial 转换到 processing
if (canTransition(currentState, 'processing')) {
currentState = 'processing';
console.log(`状态已从 ${currentState} 转换为 processing`);
} else {
console.log(`无法从 ${currentState} 转换为 processing`);
}
// 尝试从 processing 转换到 completed
if (canTransition(currentState, 'completed')) {
currentState = 'completed';
console.log(`状态已从 ${currentState} 转换为 completed`);
} else {
console.log(`无法从 ${currentState} 转换为 completed`);
}
// 尝试从 completed 转换到 rejected
if (canTransition(currentState,'rejected')) {
currentState ='rejected';
console.log(`状态已从 ${currentState} 转换为 rejected`);
} else {
console.log(`无法从 ${currentState} 转换为 rejected`);
}