MST

星途 面试题库

面试题:TypeScript复杂状态机类型转换

设计一个TypeScript状态机,包含“initial”、“processing”、“completed”和“rejected”四种状态。状态之间有以下转换规则:从“initial”可以转换到“processing”;从“processing”可以转换到“completed”或“rejected”。请使用TypeScript类型系统精确建模这些状态和转换,编写类型保护函数来确保状态转换的合法性,并提供示例代码展示状态的转换过程。
49.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义状态类型
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`);
}