Typescript:Partial<this> 作为参数类型不起作用

标签 typescript

我试图编译以下代码,但在 C.inc 方法中失败并显示消息:

error TS2345: Argument of type '{ counter: number; }' is not assignable to parameter of type 'Partial<this>'.

代码无法编译:

class B {
    clone(diff: Partial<this>): this {
        return this; // omit the implementation.
    }
}

class C extends B {
    counter = 0;
    inc() {
        return this.clone({
            counter: this.counter + 1
        })
    }
}

但是下面的代码可以编译(没有C.inc方法):

let c = new C();
c.clone({ counter: c.counter + 1 });

我想知道为什么。

最佳答案

我不知道为什么Partial<this>不起作用,但是 Pick works :

class B {
    clone<K extends keyof this>(diff: Pick<this, K>): this {
        return this; // omit the implementation.
    }
}

class C extends B {
    counter = 0;
    inc() {
        return this.clone({
            counter: this.counter + 1
        })
    }
}

我很想知道原因!

关于Typescript:Partial<this> 作为参数类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47657038/

相关文章:

javascript - Angular 如何将数据从子组件传递到父组件

reactjs - 如何在 Typescript 中定义 React Navigation navigationOptions 参数

javascript - 如何以 Angular 6 显示垫表中每一行的垫旋转器

javascript - 将常量转译为 JavaScript

javascript - TypeScript 转 js 错误

angular - <ng-select> [items] 值不更新

visual-studio-2013 - 如何在 VS2013 中强制 TypeScript 重新编译?

测试时出现 Typescript、Express、Mocha 和 Chai 错误

angular - Observable 继续调用 API 并根据条件更改参数

typescript - 使用 "anonymous"方法实现接口(interface)