提问人:Eggy 提问时间:11/14/2023 最后编辑:Eggy 更新时间:11/14/2023 访问量:58
如何覆盖扩展记录的泛型类参数?
How to overwrite generic class argument that extends record?
问:
我有一个和类。该类接受 2 个泛型参数:和 . 应该是某种类,而是以特定接口作为值的子集。现在,我的目标是创建子类,该子类将强制某些特定属性存在于 上,以便我可以强制使用该属性接口的某些自定义实现。Parent
Child
Parent
Result
ParentBuilderMap
Result
ParentBuilderMap
Result
ParentBuilderMap
我试图用 覆盖属性,但这会产生一个错误,指出这种类型不能分配给 ,我觉得这很奇怪,因为它将具有相同的键(或更多应该没问题)。Omit<A, keyof B> & B
ParentBuilderMap
下面是上述描述的演示实现
type Overwrite<A, B> = Omit<A, keyof B> & B;
interface Builder<Result> {
build(): Result;
}
class SuperSecretBuilder implements Builder<string> {
build() {
return "lorem ipsum";
}
secret() {
return "p4ssw0rd";
}
}
type BuilderMap<Result> = Partial<Record<keyof Result, Builder<unknown>>>;
class Parent<Result, ParentBuilderMap extends BuilderMap<Result>> {
doWork<Key extends keyof ParentBuilderMap>(key: Key, cb: () => ParentBuilderMap[Key]) {
// tbd
}
}
class Child<
Result,
ChildBuilderMap extends Overwrite<BuilderMap<Result>, { value: SuperSecretBuilder }>,
> extends Parent<Result, ChildBuilderMap> {
doSecretWork() {
// This method should resolve callback return value to SuperSecretBuilder based on provided key.
this.doWork("value", () => {
const builder = new SuperSecretBuilder();
console.log(builder.secret());
return builder;
});
}
}
答: 暂无答案
评论
value
Parent
类不接受兼容类型(在我看来)是这里的问题。至于为什么我在方法中需要泛型:我想在类中做一些操作。这很好用,因为有 ( 来自 .现在,我有几个子类。它们都需要对 中的某些属性进行一些具体的实现。因此,上述的目标是提取到抽象类中,以便它可以被具体类(应该扩展类)重用。doWork
Builder
Parent
Builder<unknown>
BuilderMap<Result>
Parent
Builder
BuilderMap
doSecretWork
Child
Parent
Child
Builder<Result>
doWork
ParentBuilderMap<Result>
Builder
BuilderMap
Builder
build
Parent
ChildBuilderMap
() => {
as ChildBuilderMap["value"]
Overwrite
value
Result