【发布时间】:2021-10-19 18:01:17
【问题描述】:
我想知道为什么我收到了
Type 'typeof TestBody' does not satisfy the constraint 'typeof AbstractBodyWithTabs'.
Construct signature return types 'TestBody' and 'AbstractBodyWithTabs<T, U>' are incompatible.
The types of 'contents' are incompatible between these types.
Type 'TestContent' is not assignable to type 'T'.
'TestContent' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'AbstractSelector'.
class TestPage extends PageWithTabs<typeof TestBody> {
“T”约束是正确类型的扩展类。
export class AbstractSelector {
protected readonly myRoot : Selector
constructor(inSelector : Selector) {
this.myRoot = inSelector;
}
}
export abstract class AbstractBodyWithTabs<
T extends AbstractSelector,
U extends Tabs
> {
abstract get contents () : T
abstract get tabs () : U
get wrapper () : Selector {
return Selector(".app-component");
}
}
export abstract class Tabs extends AbstractSelector {
get active () {
return this.wrapper.find(":scope > button[contains(@class, 'focus')]");
}
get all () {
return this.wrapper.find(":scope > button");
}
abstract get named_tab () : Record<string, Selector>;
get wrapper () {
return this.myRoot.find("div.btn-group");
}
}
export abstract class PageWithTabs<V extends typeof AbstractBodyWithTabs> {
abstract get body () : InstanceType<V>
get footer () {
return new SaveAndCancelFooter();
}
get header () {
return new Header();
}
}
class TestContent extends AbstractSelector {
}
class TestTabs extends Tabs {
get named_tab () {
return { get country () { return Selector("div"); } };
}
}
class TestBody extends AbstractBodyWithTabs<TestContent, TestTabs> {
get contents () {
return new TestContent(this.wrapper);
}
get tabs () {
return new TestTabs(this.wrapper);
}
}
class TestPage extends PageWithTabs<typeof TestBody> {
get body () {
return new TestBody();
}
}
当我进行这些更改时:
export abstract class PageWithTabs<V extends typeof AbstractBodyWithTabs> {
abstract get body () : InstanceType<V>
get footer () {
return new SaveAndCancelFooter();
}
get header () {
return new Header();
}
}
到
export abstract class PageWithTabs<T extends AbstractSelector, U extends Tabs, V extends AbstractBodyWithTabs<T, U>> {
abstract get body () : V
get footer () {
return new SaveAndCancelFooter();
}
get header () {
return new Header();
}
}
class TestPage extends PageWithTabs<typeof TestBody> {
get body () {
return new TestBody();
}
}
到
class TestPage extends PageWithTabs<TestContent, TestTabs, TestBody> {
get body () {
return new TestBody();
}
}
它有效,但我不喜欢我必须传递已声明的多个类型。
打字稿playground
【问题讨论】:
标签: typescript typescript-generics