【发布时间】:2021-08-30 18:01:48
【问题描述】:
我正在设计一个涉及一些有限状态机的 lib API,因此假设该 lib 导出以下接口:
export interface FSM<TStates> {
state: TStates
// ... other properties
}
该库要求状态机具有状态'started' 和'finished'。我一直在尝试将这个约束编码到类型系统中,但没有取得多大成功。
到目前为止,我已经尝试将此约束实现为枚举:
export enum BaseState {
STARTED = 'started',
FINISHED = 'finished',
}
export interface FSM<TStates extends BaseState> {
state: TStates
// ... other properties
}
enum MyState {
STARTED = 'started',
OTHER = 'other',
FINISHED = 'finished',
}
// Type 'MyState' does not satisfy the constraint 'BaseState'.ts(2344)
let fsm: Fsm<MyState>
我尝试了联合类型
export type BaseState = 'started' | 'finished';
export interface FSM<TStates extends BaseState> {
state: TStates
// ... other properties
}
type MyState = 'started' | 'finished' | 'other'
// Type 'MyState' does not satisfy the constraint 'BaseState'.
// Type '"other"' is not assignable to type 'BaseState'.ts(2344)
let fsm: Fsm<MyState>
是否可以在打字稿中表示这种约束?
【问题讨论】:
-
特别是您的联合示例,
FSM的定义声明“我在'开始'和'完成'状态下工作”。这就是为什么传入MyState不起作用的原因——FSM 没有声明它了解如何使用other状态。我在过去实现您想要的模式的一种方法是创建state字段state: BaseState & TStates,然后重构TStates以表示BaseStates之上的所有其他状态。
标签: typescript enums type-safety