gpt4 book ai didi

javascript - 将条件类型映射回联合类型?

转载 作者:搜寻专家 更新时间:2023-10-30 21:08:01 25 4
gpt4 key购买 nike

我正在尝试执行以下操作(也是 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 的条件类型来完成。


编辑:根据下面埃里克的回答,我也很好奇为什么 this one不会工作,如果有可能在不重新定义 ResponseResult 并且不更改函数的返回类型的情况下使其工作。

@埃里克,second example .

最佳答案

您需要将类型封装为(假设) typescript 不能假设(计算)两个未引用的条件类型相同。

所以改为做

type ResponseResult<T> =
T extends 'foo'
? string
: T extends 'bar'
? number
: T extends 'baz' ? boolean : never;

现在您可以将函数的签名更改为:

async function sendWorkRequest<T extends RequestType>(
type: T,
...params
): Promise<ResponseResult<T>> {

并更新p:

const p = new Promise<ResponseResult<T>>(() => { });

TypeScript Playground Example

Do you know why or how to do it without changing the return type and without modifying the definition of the return type?

否,因为 Conditional Type 不等于 Type

Does that one require an explicit type cast in the place where the function is called?

不,我可以用 type 的属性模拟 promise 并查看它是那种类型:

TypeScript Playground Example

Is there a way to make it safe (no type cast)?

没必要

关于javascript - 将条件类型映射回联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53109626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com