从概念上讲,我正在寻找的是这样的东西,但这不会编译:
const a: <T>[(v:any) => T, (t:T) => void] = [ ... ]
实际上,这与您想要的相反。根据函数类型的直觉,a: <T>(t: T) => T 意味着你有一个适用于所有类型的函数。这是一个通用量词:a 的实现不知道T 是什么; a 的用户可以将T 设置为任何他们想要的。为您的元组执行此操作将是灾难性的,因为无论T 是什么,内部函数都需要输出T 的值,因此他们唯一能做的就是错误输出/永远循环/以某种方式处于底部或另一个(他们必须返回never)。
你想要existential quantification。 a: ∃T. [(v:any) => T, (t:T) => void] 表示 a 有一些类型 T 与之关联。 a 的实现知道它是什么并且可以随心所欲地使用它,但是a 的用户现在对此一无所知。实际上,与通用量化相比,它颠倒了角色。 TypeScript doesn't have support for existential types(甚至不是像 Java 通配符这样的超级基本形式),但它是 can be simulated:
type WirePlanEntry = <R>(user: <T>(name: string, reader: (msg: any) => T, action: (t: T) => Promise<any>)) => R
type WirePlan = WirePlanEntry[]
是的,那是一口。可以分解为:
// Use universal quantification for the base type
type WirePlanEntry<T> = [string, (msg: any) => T, (t: T) => Promise<any>]
// A WirePlanEntryConsumer<R> takes WirePlanEntry<T> for any T, and outputs R
type WirePlanEntryConsumer<R> = <T>(plan: WirePlanEntry<T>) => R
// This consumer consumer consumes a consumer by giving it a `WirePlanEntry<T>`
// The type of an `EWirePlanEntry` doesn't give away what that `T` is, so now we have
// a `WirePlanEntry` of some unknown type `T` being passed to a consumer.
// This is the essence of existential quantification.
type EWirePlanEntry = <R>(consumer: WirePlanEntryConsumer<R>) => R
// this is an application of the fact that the statement
// "there exists a T for which the statement P(T) is true"
// implies that
// "not for every T is the statement P(T) false"
// Convert one way
function existentialize<T>(e: WirePlanEntry<T>): EWirePlanEntry {
return <R>(consumer: WirePlanEntryConsumer<R>) => consumer(e)
}
// Convert the other way
function lift<R>(consumer: WirePlanEntryConsumer<R>): (e: EWirePlanEntry) => R {
return (plan: EWirePlanEntry) => plan(consumer)
}
消费EWirePlanEntry看起来像
plan(<T>(eT: WirePlanEntry<T>) => ...)
// without types
plan(eT => ...)
但如果你只有这样的消费者
function consume<T>(plan: WirePlanEntry<T>): R // R is not a function of T
你会像使用它们一样
plan(consume) // Backwards!
lift(consume)(plan) // Forwards!
不过,现在你可以拥有制作人了。最简单的这种生产者已经写好了:existentialize。
这是您的其余代码:
type WirePlan = EWirePlanEntry[]
const wirePlan: WirePlan = [
existentialize(['saveModel', (msg:any) => <Model>msg.model , api.saveModel]),
existentialize(['getModel' , (msg:any) => <string>msg.modelID, api.getModel ]),
]
const handleMessage = (msg: any) => {
let entry = wirePlan.find(lift((w) => w[0] === msg.name))
if(entry) {
entry(handler => {
const extractedValue = handler[1](msg)
return handler[2](extractedValue)
})
}
}
In Action