我试图将对象中的属性(如果存在且大于0)减少1,但是无论我如何尝试,TypeScript都不会编译此代码。
interface IStatus {
[key: string]: number | undefined; // <= I don't want undefined here but it complains since the params are optional
burning?: number;
firing?: number;
}
class Thing {
public status: IStatus = {};
private processStatus() {
for (const key in this.status) {
if (
this.status.hasOwnProperty(key) &&
this !== undefined &&
this.status !== undefined &&
this.status[key] !== undefined && // <= Complains about implicit any without the index signature
this.status[key] > 0 // <= Complains about possibly undefined with the index signature
) {
this.status[key]--;
}
}
}
}
在Typescript中,具有索引签名的类型的所有属性都必须遵守该签名,这就是为什么它要求您将其包括undefined
在索引值中的原因。这是一种确保属性类型一致的机制,无论您使用括号符号(status["burning"]
)还是点符号(status.burning
)访问属性都是如此。
但是您可以通过使用交集类型来组合索引签名和其他属性来解决此问题:
type IStatus = {
[key: string]: number; // <= No undefined here anymore
} & {
burning?: number;
firing?: number;
}
使用该方法,this.status[key]
可以推断出具有type number
,但是this.status.burning
可以推断出具有type number | undefined
。
如前所述,您将要小心,因为现在您可以burning
通过访问属性的方式更改属性的推断类型。如果使用this.status["burning"]
,则类型推断为just number
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句