[英]Differentiate parts of generic union in typescript
I would like to implement following function我想实现以下功能
const foo = <S>(newState: S | ((prevState: S) => S)) => {...}
so it takes either new state of type S
or a function producing new state from the old state.所以它需要类型
S
新状态或从旧状态产生新状态的函数。
How can I differentiate between those options in the implementation?我如何区分实现中的这些选项? I assume
typeof newState === 'function'
won't work as S
can be a function just as well.我假设
typeof newState === 'function'
将不起作用,因为S
也可以是一个函数。
I'm using typescript but probably the solution would have more to do with JS then TS.我正在使用打字稿,但解决方案可能更多地与 JS 和 TS 相关。
As you mentioned, you can use typeof
to solve your problem, like:正如您所提到的,您可以使用
typeof
来解决您的问题,例如:
if(typeof newState === 'function') {
newState();
} else {
// do whatever you want
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.