![](/img/trans.png)
[英]What is the correct way to write a typescript method that expects a Promise but can return nothing if conditions aren't met?
[英]In TypeScript, what is the best way to define a function that can return either Promise<T> or Promise<T[]>?
我只是从TypeScript开始,我遇到了一种情况,在这种情况下,我正在使用的库的类型定义错误。 就我而言,该库是Massive,js , 这是类型定义 。
问题在于某些函数应该返回Promise<T[]>
或Promise<T>
,但是类型表明它始终是Promise<T[]>
。
interface Table<T> {
// other functions omitted for simplicity
save(data: object): Promise<T[]>;
insert(data: object): Promise<T[]>;
update(dataOrCriteria: object, changesMap?: object): Promise<T[]>;
}
如何修复以上函数,以便它们返回Promise<T[]>
或Promise<T>
?
您可以定义多种类型。
interface Table<T> {
// other functions omitted for simplicity
save(data: object): Promise<T | T[]>;
insert(data: object): Promise<T | T[]>;
update(dataOrCriteria: object, changesMap?: object): Promise<T | T[]>;
}
或者在使用库时,只需将T设置为项目数组即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.