【发布时间】:2019-04-06 04:05:00
【问题描述】:
我正在尝试执行以下操作(也是 see it on TypeScript playground),但函数的返回类型出现错误,告诉我条件类型无法分配给联合:
type RequestType =
| 'foo'
| 'bar'
| 'baz'
interface SomeRequest {
id: string
type: RequestType
sessionId: string
bucket: string
params: Array<any>
}
type ResponseResult = string | number | boolean
async function sendWorkRequest<T extends RequestType>(
type: T,
...params
): Promise<
T extends 'foo'
? string
: T extends 'bar'
? number
: T extends 'baz' ? boolean : never
> {
await this.readyDeferred.promise
const request: SomeRequest = {
id: 'abc',
bucket: 'bucket',
type,
sessionId: 'some session id',
params: [1,'two',3],
}
const p = new Promise<ResponseResult>((/*...*/) => {/*...*/})
this.requests[request.id] = p
this.worker.postMessage(request)
return p // <-------------------------------- ERROR
}
基本上,我希望条件类型产生ResponseResult 类型之一。因此,根据传递给函数的 type 参数,它应该返回 ResponseResult 联合中的一种类型(作为 Promise)。
我怎样才能做到这一点,以便 type 参数的类型决定返回的 Promise 的类型?
这里是another way 不使用条件类型,但我想知道是否可以使用type arg 的条件类型来完成。
编辑:根据 Erik 在下面的回答,我也很好奇为什么 this one 不起作用,以及是否可以在不重新定义 ResponseResult 且不更改函数的返回类型的情况下使其工作。
@Erik,second example。
【问题讨论】:
-
一旦你声明了你的
SomeRequest.RequestType,你永远无法在编译时知道实际的类型。为什么不将SomeRequest<TType extends RequestType>与type: TType作为属性? -
@PatrickRoberts 没关系,这只是类型的问题。实际上它会得到解决。
-
@ErikPhilips 不完全确定您的意思。介意编辑我的游乐场示例吗?
标签: javascript typescript generics conditional-types