来自这里How to infer a class method unknown return type and use it in a property
try 推断initialize
方法返回的内容并将此类型应用于prop
.
此代码有效:
class Base {
method_1() {}
}
class Child extends Base {
method_2() {}
}
abstract class AbstractClass {
prop: ReturnType<this['initialize']>
abstract initialize(): Base
}
class UserClass2 extends AbstractClass {
initialize() {
return new Child()
}
someMethod() {
this.prop.method_1() // Valid, no TS error
this.prop.method_2() // Valid, no TS error
}
}
这总是返回Base类型:
class Base {
method_1() {}
}
class Child extends Base {
method_2() {}
}
abstract class AbstractClass {
prop: ReturnType<typeof this.initialize>
abstract initialize(): Base
}
class UserClass2 extends AbstractClass {
initialize() {
return new Child()
}
someMethod() {
this.prop.method_1() // Valid, no TS error
this.prop.method_2() // Error!
}
}
在ReturnType
中使用点记法ReturnType<typeof this.initialize>
的索引方式ReturnType<this['initialize']>
和typeof
之间有什么区别?