相关疑难解决方法(0)

TypeScript条件类型 - 过滤掉只读属性/仅选择必需的属性

在TypeScript中使用新的条件类型(或者可能是另一种技术),有没有办法根据修饰符从界面中选择某些属性?例如,有......

interface I1 {
    readonly n: number
    s: string
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个基于前一个类型的新类型,如下所示:

interface I2 {
    s: string
}
Run Code Online (Sandbox Code Playgroud)

typescript conditional-types typescript2.8

10
推荐指数
1
解决办法
2034
查看次数

如何从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
查看次数