typescript - 从抽象类扩展的类中的抽象方法的键入问题
问题描述
我目前在尝试从抽象类/方法中实现 getter 时遇到问题
class Base {
get base () {
return "base";
}
}
class Content1 extends Base {
get content1 () {
return "string";
}
}
class Content2 extends Base {
get content2 () {
return 123;
}
}
class MyBody<T extends typeof Base> {
protected myContent : T
constructor (inContent : T) {
this.myContent = inContent
}
get content () {
return new this.myContent() as InstanceType<T>;
}
}
abstract class Page<T extends typeof Base> {
protected myRoot : string
constructor (inRoot : string) {
this.myRoot = inRoot;
}
abstract get body () : MyBody<T>
}
class Page1<T extends typeof Base> extends Page<T> {
get body () { // <----------------- issue here
return new MyBody(Content1);
}
}
const p1 = new Page1("abc");
p1.body.content
class NotAbstractedPage { // <------ this is fine however
protected myRoot : string
constructor (inRoot : string) {
this.myRoot = inRoot;
}
get body () {
return new MyBody(Content1);
}
}
const np = new NotAbstractedPage("abc");
np.body.content.content1;
错误是
Property 'body' in type 'Page1<T>' is not assignable to the same property in base type 'Page<T>'.
Type 'MyBody<typeof Content1>' is not assignable to type 'MyBody<T>'.
Type 'typeof Content1' is not assignable to type 'T'.
'typeof Content1' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'typeof Base'.(2416)
(property) Page1<T extends typeof Base>.body: MyBody<typeof Content1>
我尝试将其转换为,typeof MyBody<T>
但这只会产生更多错误。
解决方案
没关系,我意识到我只需要将预期的类型放入扩展部分。
原来的
class Page1<T extends typeof Base> extends Page<T> {
get body () {
return new MyBody(Content1);
}
}
使固定
class Page1 extends Page<typeof Content1> {
get body () {
return new MyBody(Content1);
}
}
推荐阅读
- c# - C# selenium chromedriver 代理身份验证
- rx-java - RxJava - 即使调用 onNext() 如何阻止 PublishSubject 发布
- python - 如何使用正则表达式验证用户输入,并选择使用逗号输入多个条目?
- windows - 以 Azure AD 用户身份登录 Windows 10 服务
- katalon-studio - 在 Katalon 中捕获复制粘贴
- node.js - nodejs-express - 在主数据库上实现 Redis 缓存作为 mongodb
- sql - 如何计算 SQL 组中两个值的比率?
- r - 提取数据帧中最大单调递增/递减序列的元素
- javascript - 如何映射列表并在其中实现异步?
- database - 对于由多个不同服务共享的简单数据库(本质上只是一个键/值存储),最好的 AWS 服务是什么?