首页 > 解决方案 > 当源类型具有不同原始类型的属性时,映射类型会产生错误

问题描述

我有以下类型readonly从属性和只读数组中删除修饰符:

type Mutable<T> = {
    -readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? U[] : T[P];
};

class ClassWithReadOnlyProperties {
    readonly FirstName!: string;
    readonly LastName!: string;
    readonly MiddleNames!: readonly string[];

    dothing() {
        let mutable = this as Mutable<ClassWithReadOnlyProperties>;  // Works
        mutable.MiddleNames[0] = "someValue";                        // Works
    }
}

上面的代码有效。添加新number属性:

class AnotherClassWithReadOnlyProperties {
    readonly FirstName!: string;
    readonly LastName!: string;
    readonly MiddleNames!: readonly string[];
    readonly Age!: number;

    dothing() {
        let mutable = this as Mutable<AnotherClassWithReadOnlyProperties>; // Error
        mutable.MiddleNames[0] = "someValue";
    }
}

导致此错误:

将“this”类型转换为“Mutable”类型可能是一个错误,因为这两种类型都没有与另一种充分重叠。如果这是故意的,请先将表达式转换为“未知”。“AnotherClassWithReadOnlyProperties”类型与“Mutable”类型不可比较。属性“MiddleNames”的类型不兼容。'readonly string[]' 类型是 'readonly' 并且不能分配给可变类型 'string[]'。(2352)

添加任何非原始属性都可以正常工作,就像使所有属性成为相同的原始类型一样 - 仅向类中的其他原始类型添​​加不同类型的新原始类型似乎会导致错误。数组的类型似乎无关紧要。

这是在 TypeScript 3.6.3 及更高版本中 - 相同的代码在 TypeScript 3.5.1 中不会导致错误。

为什么会这样?

标签: typescript

解决方案


推荐阅读