下面是我正在做的一个简单的例子:
enum Type {A, B}
class Base<T extends Type> {
constructor(public type: T) {}
static create<T extends Type>(type: T): Base<T> {
return new Base(type);
}
}
class A extends Base<Type.A> {
static override create(): A {
return super.create(Type.A);
}
}
但我发现了一个错误:
Class static side 'typeof A' incorrectly extends base class static side 'typeof Base'.
The types returned by 'create(...)' are incompatible between these types.
Type 'A' is not assignable to type 'Base<T>'.
Type 'Type.A' is not assignable to type 'T'.
'Type.A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Type'. ts(2417)
为什么会这样呢?当我显式地从'T' could be instantiated with a different subtype of constraint 'Type'
扩展时,我不明白“Base<Type.A>
”是怎么回事。如何在此基础上创建基类的专门化?
发布于 2022-09-15 14:31:19
我们在此有几个问题:
javascript class Base<T extends Type>
意味着您必须提供扩展类型的T。但是您提供了一个值javascript class A extends Base<Type.A>
在value/instance.泛型中,只能提供类型的,而不能提供类型的。示例:
class Animal {}
class Cat extends Animal {}
class AnimalInfo<T extends Animal> {}
const catInfo = new AnimalInfo<Cat>(); //valid - we provide type
const catInstane = new Cat();
const anotherCatInfo = new AnimalInfo<catInstane>(); // not valid
一个有效的,虽然不是非常有用的例子是:
enum Type {
A,
B,
}
enum AnotherType {
C,
}
type CombinedEnum = Type & AnotherType;
class Base<T extends Type> {
constructor(public type: T) {}
static create<T extends Type>(type: T): Base<T> {
return new Base(type);
}
}
class A extends Base<CombinedEnum> {
}
方法可以是实例方法
javascript static override create() ...
不是一个有效的结构。
static method(): Something {
return super.method();
}
一个有效的结构是:
class BaseClassType {
static method(): Something {
//...
}
}
class AnotherClass {
static method(): Something {
return BaseClassType.method();
}
}
https://stackoverflow.com/questions/73731523
复制相似问题