小编Edu*_*cko的帖子

如何从typescript中的type中排除getter only属性

类中的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?

在操场上的例子

getter types typescript typescript2.0

4
推荐指数
2
解决办法
1643
查看次数

标签 统计

getter ×1

types ×1

typescript ×1

typescript2.0 ×1