【发布时间】:2019-08-03 05:09:31
【问题描述】:
如下所列,假设我们有:
- 一个函数
r将多个任务组合在一起 - 和一个函数
o,它返回一个类似when(cb).map(cb)的形状
传递给when 或map 的每个回调都应始终采用这些3 参数:S, A, C 其中S 和C 在r 中定义,A 在o 中定义.
这里是typescript playground 的链接,它也显示了我遇到的错误。
我的问题是:如何获得类型安全声明?
type Task<S, A, C> = <AA extends A>(s: S, a: AA, c: C) => any;
type Fn<S, A, C> = (s: S, a: A, c: C) => any;
const r = <S, C>() => ({
tasks: (...tasks: Task<S, any, C>[]) => null,
});
const o = <T, A = { prop: T }>(type: T) => ({
when: <S, C>(fp: Fn<S, A, C>) => ({
map: <SS extends S, CC extends C>(fn: Fn<SS, A, CC>): Task<SS, A, CC> => (
(s: SS, a: A, c: CC): any => (
fp(s, a, c) ? fn(s, a, c) : s
)
),
}),
});
const result = r<2, 7>().tasks(
o(44) // expect: cb(2, 44, 7)
.when((s, a, c) => s + a.prop + c)
.map((s, a, c) => s + a.prop + c),
o(78) // expect: cb(2, 78, 7)
.when((s, a, c) => s + a.prop + c)
.map((s, a, c) => s + a.prop + c),
// etc...
// callback provided to `.map` is typesafe,
// callback provided to `.when` is not,
);
如您所见,提供给when 的回调不是类型安全的:参数S 和C 丢失。
【问题讨论】:
标签: javascript typescript typescript-typings typescript-types typescript-definitions