首页 > 解决方案 > 在 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]”。

我该如何正确投射?

标签: angulartypescript

解决方案


TypeScript 编译器正在推断keyto的类型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;
         }
    }
}

推荐阅读