我正試圖解決這個問題。我一直在使用 Java 和 C# 中的泛型,但最近才使用 TypeScript。那么,有人可以向我解釋一下這種瘋狂嗎?
建構式 FooAdapter(): FooAdapter
型別“FooAdapter”不可分配給型別“A”。
“FooAdapter”可分配給“A”型別的約束,但“A”可以用約束“FooAdapter”的不同子型別來實體化。
ts(2322)
從以下代碼段:
interface IFoo {}
interface IAdapter<F extends IFoo> {
getFoo():F
}
abstract class AbstractFoo<F extends IFoo> {
abstract something<A extends IAdapter<F>>():A;
}
class Foo implements IFoo {}
class FooAdapter implements IAdapter<Foo> {
getFoo() { return new Foo(); }
}
class FooFactory extends AbstractFoo<Foo> {
something<A extends FooAdapter>():A {
return new FooAdapter(); // <--- ts(2322) here
}
}
如何修復此錯誤?
uj5u.com熱心網友回復:
問題是FooAdapter不是A,FooAdapter可能只是父類的A。
您的選擇是:
A)使something回傳更通用,以便它滿意new FooAdapter():
interface IFoo {}
interface IAdapter<F extends IFoo> {
getFoo():F
}
abstract class AbstractFoo<F extends IFoo> {
abstract something(): IAdapter<F>;
}
class Foo implements IFoo {}
class FooAdapter implements IAdapter<Foo> {
getFoo() { return new Foo(); }
}
interface IHasEmptyConstructor<T> {
new(): T
}
class FooFactory extends AbstractFoo<Foo> {
something(): IAdapter<Foo> {
return new FooAdapter();
}
}
const fooFactory = new FooFactory();
fooFactory.something();
B)something回傳A而不是FooAdapter:
interface IFoo {}
interface IAdapter<F extends IFoo> {
getFoo():F
}
abstract class AbstractFoo<F extends IFoo> {
abstract something<A extends IAdapter<F>>(adapter: IHasEmptyConstructor<A>):A;
}
class Foo implements IFoo {}
class FooAdapter implements IAdapter<Foo> {
getFoo() { return new Foo(); }
}
interface IHasEmptyConstructor<T> {
new(): T
}
class FooFactory extends AbstractFoo<Foo> {
something<A extends FooAdapter>(adapter: IHasEmptyConstructor<A>): A {
return new adapter();
}
}
const fooFactory = new FooFactory();
fooFactory.something(FooAdapter);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510440.html
標籤:打字稿仿制药
