typescript - 当源类型具有不同原始类型的属性时,映射类型会产生错误
问题描述
我有以下类型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 中不会导致错误。
为什么会这样?
解决方案
推荐阅读
- python - Python:PD.ExcelWriter 不追加数据
- python - Python-requests [('Connection aborted.', TimeoutError(10060) ]
- javascript - 从列中获取数组值
- android - 如何修复在较小屏幕中被截断的选择器对话框?
- mongodb - 如何对具有共同第一阶段的两个查询使用相同的 MongoDb 管道?
- gdb - 使用 gdb 摆脱悬而未决的民意调查
- r - 正确使用 doSNOW 或 doParallel 进行简单的重复性任务
- recursion - Prolog 中的嵌套谓词
- python - 如何绘制 K-means 并打印集群外的点
- powershell - Get-Modules 中缺少 NetTCPIP 一分钟