这是我的代码,用于测试某些类对象的相等性。如果您想知道为什么我不只是在做,请参阅我的other question
expect(receivedDeals).toEqual(expectedDeals)
和其他更简单的断言。
type DealCollection = { [key: number]: Deal }; // imported from another file
it("does the whole saga thing", async () => {
sagaStore.dispatch(startAction);
await sagaStore.waitFor(successAction.type);
const calledActionTypes: string[] = sagaStore
.getCalledActions()
.map(a => a.type);
expect(calledActionTypes).toEqual([startAction.type, successAction.type]);
const receivedDeals: DealCollection = sagaStore.getLatestCalledAction()
.deals;
Object.keys(receivedDeals).forEach((k: string) => {
const id = Number(k);
const deal = receivedDeals[id];
const expected: Deal = expectedDeals[id];
for (let key in expected) {
if (typeof expected[key] === "function") continue;
expect(expected[key]).toEqual(deal[key]);
}
});
});
测试通过了,但是我在expected[key]
上遇到了Flow错误:
Cannot get 'expected[key]' because an index signature declaring the expected key / value type is missing in 'Deal'
我可以根据请求从Deal
粘贴代码,但是我想您需要知道的是我还没有声明索引签名(因为我不知道怎么做!)。
我搜索了一下,但找不到确切的情况。
更新:我可以通过这样更改deal
和expected
来消除错误:
const deal: Object = { ...receivedDeals[id] };
const expected: Object = { ...expectedDeals[id] };
由于我正在比较循环中的属性,所以这实际上不是问题。但是我认为我应该能够使用Deal
来做到这一点,而且我想知道如何声明错误中提到的索引签名。
PS。额外的问题:在一个疯狂的科学家与Swift杂交JS的世界中,我想您可以做类似的事情
const deal: Object = { ...receivedDeals[id] where (typeof receivedDeals[id] !== "function" };
const expected = // same thing
expect(deal).toEqual(expected);
// And then after some recombining of objects:
expect(receivedDeals).toEqual(expectedDeals);
这是一回事吗?
添加一些Deal
类的定义:
export default class Deal {
obj: { [key: mixed]: mixed };
id: number;
name: string;
slug: string;
permalink: string;
headline: string;
// ...other property definitions
constructor(obj?: Object) {
if (!obj) return;
this.id = obj.id;
this.name = obj.name;
this.headline = obj.headline;
// ...etc
}
static fromApi(obj: Object): Deal {
const deal = new Deal();
deal.id = obj.id;
deal.name = obj.name;
deal.slug = obj.slug;
deal.permalink = obj.permalink;
// ...etc
return deal;
}
descriptionWithTextSize(size: number): string {
return this.descriptionWithStyle(`font-size:${size}`);
}
descriptionWithStyle(style: string): string {
return `<div style="${style}">${this.description}</div>`;
}
distanceFromLocation = (
location: Location,
unit: unitOfDistance = "mi"
): number => {
return distanceBetween(this.location, location);
};
distanceFrom = (otherDeal: Deal, unit: unitOfDistance = "mi"): number => {
return distanceBetween(this.location, otherDeal.location);
};
static toApi(deal: Deal): Object {
return { ...deal };
}
static collectionFromArray(array: Object[]) {
const deals: DealCollection = {};
array.forEach(p => (deals[p.id] = Deal.fromApi(p)));
return deals;
}
}
答案 0 :(得分:1)
索引签名(或索引器属性)定义为[keyName: KeyType]: ValueType
。 DealCollection
是一个很好的例子:keyName
是key
,KeyType
是number
,而ValueType
是Deal
。这意味着每当您访问类型为DealCollection
的对象的数字属性时,它将返回一个Deal
。您将需要向Deal
的定义添加类似的表达式,以便访问其上的任意属性。可以在Flow文档的Objects as maps部分中找到更多信息。