我想尽可能做到最好,所以我首先判断propertyKey
是否是objectParent
的属性.这是我的playground 代码
const objectParent = {
product: 'this is product',
shipping: 'this is shipping',
};
const firstOne = false;
const displayOrder = firstOne
? (['a', 'b'] as const)
: (['a', 'b', 'c', 'product', 'shipping'] as const);
for (const propertyKey of displayOrder) {
if (propertyKey in objectParent) {
console.log(objectParent[propertyKey]);
}
}
我希望因为我已经添加了一个使用if (propertyKey in objectParent)
的TypeGuard,所以TypeScrip应该允许我使用propertyKey
作为索引.我知道使用propertyKey as keyof typeof objectParent
可以绕过这一步,但我觉得这不是一个解决方案,因为编写起来有点懒惰