【发布时间】:2021-06-28 08:18:46
【问题描述】:
我正在玩弄一些逻辑来创建一个强类型工作者,它应该只能接受一组预定义的消息,并根据给定的消息以适当的响应类型进行响应。
类似下面的东西
type MsgStruct<T, P, R> = {
type: T
payload: P
response: R
}
type FooMsg = MsgStruct<'foo', number, number>
type BarMsg = MsgStruct<'bar', boolean, string>
type BazMsg = MsgStruct<'baz', string, boolean[]>
// Messages that can be handled by the worker
type WorkerMsg =
| FooMsg
| BarMsg
| BazMsg
// Creation logic
type StronglyTypedWorker<T> = T extends { type: infer A, payload: infer B, response: infer C } ? {
postMessage: (msg: { type: A, payload: B }) => Promise<C>
} : never
declare const worker: Worker
declare const createWorker: <T extends MsgStruct<unknown, unknown, unknown>>(worker: Worker) => StronglyTypedWorker<T>
// Example
const strongWorker = createWorker<WorkerMsg>(worker)
declare const foo: FooMsg
const fooRes = strongWorker.postMessage(foo)
.then(res => {}) // expecting `res` to be of type `number` here
这不起作用,因为 tsc 抱怨
“FooMsg”类型的参数不能分配给“never”类型的参数。 交集 '{ type: "foo";有效载荷:数字; } & { 类型:“酒吧”;有效载荷:布尔值; } & { 类型:“baz”;有效载荷:字符串; }' 被简化为 'never' 因为属性 'type' 在某些成分中具有冲突类型。ts(2345)
有没有更好的方法来做到这一点?或者更确切地说,一个有效的?
【问题讨论】:
标签: typescript