gpt4 book ai didi

angular - Typescript 编译器不知道类上的 ES6 代理陷阱

转载 作者:太空狗 更新时间:2023-10-29 18:12:27 26 4
gpt4 key购买 nike

我有一个抽象类:

abstract class Foo {
abstract bar(): string;
}

我有一些扩展 Foo 的类:

class Foo1 extends Foo {
bar(): string { return 'foo1'; }
}

class Foo2 extends Foo {
bar(): string { return 'foo2'; }
}

我有另一个类,我想将 Foo 的所有方法代理到 Foo。如果我在此类上定义 Foo 的所有方法,这实际上工作正常。但我宁愿不那样做。我希望在 Foo 上定义 Foo 的方法,并且编译器知道 FooProxy 也实现了这些方法,而无需实际实现它们.这可能吗? Proxy 类看起来像这样:

class FooProxy {
public foo: Foo;

constructor(foo: Foo) {
this.foo = foo;
let handler = {
get: function(target: FooProxy, prop: string, receiver: any) {
if(Foo.prototype[prop] !== null) {
return target.foo[prop];
}

return Reflect.get(target, prop, receiver);
}
}
return new Proxy(this, handler);
}
}

示例:

let f = new Foo1();
let fp = new FooProxy(f);
fp.bar();

输出:

error TS2339: Property 'bar' does not exist on type 'FooProxy'.

这个程序实际上在 playground 中运行,但是 tsc 没有发出任何东西。我只需要以某种方式欺骗编译器...

最佳答案

我不认为在这种情况下类是最好的方法,您可以只使用一个函数来创建代理,并且一切都会按预期工作:

function createFooProxy(foo:Foo) : Foo { // Proxy<Foo> is compatible with Foo
let handler = {
get: function(target: Foo, prop: keyof Foo, receiver: any) {
if(Foo.prototype[prop] !== null) {
return foo[prop];
}

return Reflect.get(target, prop, receiver);
}
}
return new Proxy(foo, handler);
}

如果你开始使用类方法,你可以伪造一个基类:

function fakeBaseClass<T>() : new() => Pick<T, keyof T>{ // we use a pick to remove the abstract modifier
return class {} as any
}

class FooProxy extends fakeBaseClass<Foo>(){
private foo: Foo; // I would make this private as it is not really accessible on what the constructor of FooProxy returns (maybe remove it as I see no use for it)

constructor(foo: Foo) {
super();
this.foo = foo;
let handler = {
get: function(target: FooProxy, prop: keyof Foo, receiver: any) {
if(Foo.prototype[prop] !== null) {
return target.foo[prop];
}

return Reflect.get(target, prop, receiver);
}
}
return new Proxy(this, handler);
}
}

关于angular - Typescript 编译器不知道类上的 ES6 代理陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com