Typescript:具有来自数组值的键的动态对象
我创建了一个类来批量处理承诺,并根据它们在中给出的键返回结果。例如,若您给它两个名为Typescript:具有来自数组值的键的动态对象,typescript,class,Typescript,Class,我创建了一个类来批量处理承诺,并根据它们在中给出的键返回结果。例如,若您给它两个名为order和customer的键,每个键都有一个承诺,它将解析这些承诺并返回一个对象,其中这些键作为属性,解析的值作为各自的值 下面是如何使用这个类: const batchPromiseHandler = new BatchPromise(); // getCustomerInfo and getPaymentInfo will give back a promise which resolves into
order
和customer
的键,每个键都有一个承诺,它将解析这些承诺并返回一个对象,其中这些键作为属性,解析的值作为各自的值
下面是如何使用这个类:
const batchPromiseHandler = new BatchPromise();
// getCustomerInfo and getPaymentInfo will give back a promise which resolves into their data
batchPromiseHandler.add('order', getOrderInfo());
batchPromiseHandler.add('customer', getCustomerInfo());
// await to resolve all into result object
const result = await batchPromiseHandler.resolveAll();
console.log(result.order); // <<-- I want to be able to get suggestion order or customer from IDE
console.log(result.customer);
我如何重构它以获得IDE向我建议的
订单
或客户
?这里的问题是类型BatchPromise
不知道它所持有的特定键和值。如果您想让它跟踪这一点,它需要是类似于BatchPromise
的类型,其中T
是表示resolveAll()
中返回的键到值映射的对象类型
为了使其工作,您需要更改调用add()
的方式,以合并而不是多个语句:
const batchPromiseHandler = new BatchPromise()
.add('order', getOrderInfo())
.add('customer', getCustomerInfo());
这样,您的batchPromiseHandler
将属于类似BatchPromise
的类型
让我们看看这是否有效:
const result = await batchPromiseHandler.resolveAll();
result.customer; // CustomerInfo
result.order; // OrderInfo
result.randomThing; // error!
// Property 'randomThing' does not exist on type
// 'Record<"order", OrderInfo> & Record<"customer", CustomerInfo>'
const result=await batchPromiseHandler.resolveAll();
result.customer;//客户信息
result.order;//订单信息表
result.randomThing;//错误!
//类型上不存在属性“randomThing”
//“记录&记录”
看起来不错。您可以验证(通过下面的游乐场链接)IDE的IntelliSense将能够提示结果
具有客户
和订单
属性
好吧,希望这能给你一个前进的方向。祝你好运
class BatchPromise<T extends object = {}> {
...
async resolveAll(): Promise<T> { ... }
}
add<K extends string, V>(
key: K, promise: Promise<V>, decorator?: resultDecorator
): BatchPromise<T & Record<K, V>> {
...
return this as BatchPromise<T & Record<K, V>>;
}
const batchPromiseHandler = new BatchPromise()
.add('order', getOrderInfo())
.add('customer', getCustomerInfo());
const result = await batchPromiseHandler.resolveAll();
result.customer; // CustomerInfo
result.order; // OrderInfo
result.randomThing; // error!
// Property 'randomThing' does not exist on type
// 'Record<"order", OrderInfo> & Record<"customer", CustomerInfo>'