Typescript 带流量的正确类型检查减速器
我尝试将Flow与Redux代码库集成。Typescript 带流量的正确类型检查减速器,typescript,redux,flowtype,Typescript,Redux,Flowtype,我尝试将Flow与Redux代码库集成。 我对Flow很陌生,但我已经玩过一点TypeScript了 我希望能够捕捉到减速器内的错误动作类型 type Action = | { type: 'sample' } | { type: 'django' } ; type State = { content: string, }; const reducer = (state: State, action: Action): State => { switch (a
我对Flow很陌生,但我已经玩过一点TypeScript了 我希望能够捕捉到减速器内的错误动作类型
type Action =
| { type: 'sample' }
| { type: 'django' }
;
type State = {
content: string,
};
const reducer = (state: State, action: Action): State => {
switch (action.type) {
// OK
case 'sample':
return { content: '' };
// Should raise a type error, because the action type
// will never be equal to "error"
case 'error':
return { content: '' };
default:
return { content: '' };
}
};
我不明白为什么Flow在这种情况下没有捕捉到错误。 Flow将
类型
属性推断为字符串
,但我明确地将类型设置为'sample'|'django'
我错过什么了吗
谢谢 这看起来像是流程中的一个bug,但您可以执行严格的验证,如下所示:
type ActionType = 'sample' | 'django'
type Action = {type: ActionType}
type State = {
content: string,
};
const reducer = (state: State, action: Action): State => {
const type:ActionType = action.type;
switch (type) {
// Should raise a type error, because the action type
// will never be equal to "error"
case 'error':
return { content: '' };
default:
return { content: '' };
}
};
这使得:
13: case 'error':
^ string literal `error`. This type is incompatible with
9: const type:ActionType = action.type;
^ string enum
确实是一个bug/正在进行的工作-请参阅