javascript-将条件类型映射回联合类型?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-将条件类型映射回联合类型?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2055字,纯文字阅读大概需要3分钟。
内容图文
![javascript-将条件类型映射回联合类型?](/upload/InfoBanner/zyjiaocheng/669/3e210e66cffc4752975c9c168bda2867.jpg)
我正在尝试执行以下操作(也为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在不使用条件类型的情况下执行的操作,但是我想知道是否可以使用arg类型的条件类型来完成操作.
编辑:基于下面的Erik的回答,我也很好奇为什么this one无法正常工作,并且是否有可能在不重新定义ResponseResult且不更改函数返回类型的情况下使其工作.
@ Erik,second example.
解决方法:
您需要将Type封装为(假设)打字稿,不能假定(计算)两个未引用的条件类型相同.
所以做
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>>(() => { });
Do you know why or how to do it without changing the return type and without modifying the definition of the return type?
否,因为条件类型不等于类型.
Does that one require an explicit type cast in the place where the function is called?
不,我可以使用类型的属性来模拟promise,并查看它是否属于该类型:
Is there a way to make it safe (no type cast)?
不必要
内容总结
以上是互联网集市为您收集整理的javascript-将条件类型映射回联合类型?全部内容,希望文章能够帮你解决javascript-将条件类型映射回联合类型?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。