【发布时间】:2019-10-04 09:34:46
【问题描述】:
如何为函数createWrapper 编写泛型类型,以使示例末尾的返回类型与指定的一样?
function createWrapper(wrapper) {
return fn => wrapper(fn);
}
const wrap = createWrapper(fn => {
if (Math.random() < 0.5) {
return 4 as const;
}
const result = fn();
return result === 0 ? null : result;
});
const nullOrOneOrFour = wrap(() => {
return Math.random() < 0.5 ? (0 as const) : (1 as const);
});
const twoOrThreeOrFour = wrap(() => {
return Math.random() < 0.5 ? (2 as const) : (3 as const);
});
// ReturnType<typeof nullOrOneOrFour> -> null | 1 | 4
// ReturnType<typeof nullOrTwoOrThreeOrFour> -> null | 2 | 3 | 4
函数createWrapper 的定义是唯一需要显式类型注释的区域。理想情况下,其他一切都可以推断出来。
在玩了更多之后,我想我可能需要像高阶类型这样的东西才能正确地做到这一点(即泛型泛型)。这条评论似乎与我想要完成的事情有关:https://github.com/microsoft/TypeScript/issues/1213#issuecomment-523245130。
【问题讨论】:
-
抱歉,createWrapper 的代码是什么。这不是你想要输入的内容
-
@jstuartmilne 我添加了
createWrapper的代码 -
在评论中你提到了
nullOrTwoOrThreeOrFour,但在代码中你有twoOrThreeOrFour。评论应该是twoOrThreeOrFour吗?
标签: typescript