在TypeScript中使用新的条件类型(或者可能是另一种技术),有没有办法根据修饰符从界面中选择某些属性?例如,有......
interface I1 {
readonly n: number
s: string
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个基于前一个类型的新类型,如下所示:
interface I2 {
s: string
}
Run Code Online (Sandbox Code Playgroud) 类中的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?