[英]How to assert a discriminated union is of a certain variant in typescript unit tests?
[英]How can I write an assert function to assert a discriminated union type?
我有一个受歧视的工会:
type State =
{ tag: "A", /* other props */ }
| { tag: "B", /* other props */ }
现在我有一段代码只能在某个state工作:
// Somewhere
const state: State = …;
// And later elsewhere
if (state.tag !== "A") {
throw new AssertionError(…);
}
// Here I am sure `state` is of type A
我可以将条件重写为断言 function 吗?
// Somewhere
const assertState = (state: State, tag: State["tag"]) => ???
// And later:
assertState(state, "A");
// Here I am sure `state` is of type A
这可以使用断言函数来完成。
type State =
{ tag: "A", /* other props */ }
| { tag: "B", /* other props */ }
function assertState (condition: boolean): asserts condition {
if (!condition) {
throw new Error("message")
}
}
function test(){
let state: State = {} as any
assertState(state.tag === 'A')
state.tag // is only of type `A` now
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.