angular - 在 Typescript 中进行类型转换
问题描述
我有这门课:
export class AccountApprovedColumnFilter {
public showRowNumber: boolean = true;
public showImage: boolean = true;
public showProduct: boolean = true;
public showCategory: boolean = true;
public showGender: boolean = true;
public showSupplyingAccount: boolean = true;
public showSalesOrder: boolean = true;
public showRequestedUnits: boolean = true;
public showApprovedUnits: boolean = true;
public showSizeDetails: boolean = true;
public showSubmit: boolean = true;
public reset(): void {
for (let key in this) {
if (this.hasOwnProperty(key)) {
this[key] = true;
}
}
}
}
但 Visual Studio 抱怨这一行:
this[key] = true;
类型“true”不可分配给类型“this[keyof this]”。
我该如何正确投射?
解决方案
TypeScript 编译器正在推断key
to的类型keyof this
,无论出于何种原因,它都无法静态验证是否可以将 的所有可能值this[keyof this]
设置为布尔值。
您可以通过在函数签名中提供显式类型来解决此问题:
public reset(this: AccountApprovedColumnFilter): void {
...
}
这将在最终输出中被删除(即它不会向您的方法添加额外的参数)。
请注意,直到 TypeScript 2.0 才添加此功能 - 如果您因某种原因被困在旧版本上,另一种解决方法是this
在您的循环中强制转换:
public reset(): void {
for (let key in this as AccountApprovedColumnFilter) {
if (this.hasOwnProperty(key)) {
this[key] = true;
}
}
}
在最坏的情况下,您可以创建一个临时变量并为其指定显式类型:
public reset(): void {
const self: AccountApprovedColumnFilter = this;
for (let key in self) {
if (self.hasOwnProperty(key)) {
self[key] = true;
}
}
}
推荐阅读
- java - 使用 jpa 规范检索有限的列
- postgresql - 需要帮助将 CASE 中的集合返回函数移动到 LATERAL 连接
- r - 在 R 中打印到 pdf 时打印到控制台
- caching - 当 L1 访问延迟较高时,用于有用工作的处理器周期会减少
- python - Flask 使用 id 来个性化登陆页面
- php - WP All Import 不从自定义字段导入值
- php - Word 文档 Base64 编码字符串下载为 zip 文件
- c# - 如何根据checkedlistbox C#中各自的复选框从列表中返回项目?
- python - 无法从 DHT 传感器获取数据
- javascript - 如何在单击按钮后淡入 css 消息 3 秒?