类中的getters是只读属性,因此从下面的代码中抛出类型错误是有意义的.
class Car {
engine: number;
get hp() {
return this.engine / 2;
}
get kw() {
return this.engine * 2;
}
}
function applySnapshot(
car: Car,
snapshoot: Partial<Car> // <-- how to exclude readonly properties?
) {
for (const key in snapshoot) {
if (!snapshoot.hasOwnProperty(key)) continue;
car[key as keyof Car] = snapshoot[key as keyof Car];
// Cannot assign to 'hp' because it is a constant or a read-only property.
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法如何投射可写的属性来键入和排除所有的getter?