Scenario:我正在try 创建一个基本方法,我可以对需要进行的几个不同调用重复使用(works
/doesNotWork
).基本方法应该进行一些设置,因为我不想重复几次.问题是,我传递给Setup调用的泛型告诉我它需要一个不同的类型.我需要的所有属性都存在于基本泛型类型上,但我遇到了打字问题.
Error:Argument of type '{ SyncCount: number; }' is not assignable to parameter of type 'DeepPartial<T>'
.
Goal:我想要一个使用泛型的解决方案,它将允许我有一个基本方法,我可以调用设置.理想情况下,doesNotWork
应该经过修改才能正常工作.AOS,请参见下面示例和小提琴中的所需代码(目标).
这是我issue美元中的一把小提琴
type DeepPartial<T> = T extends object ? {
[P in keyof T]?: DeepPartial<T[P]>;
} : T;
interface IDbRecord {
readonly _id: string;
readonly _rev: string;
readonly DocumentType: string;
}
interface IBuilder<TEntity extends IDbRecord> {
defaults(value: DeepPartial<TEntity>): Builder<TEntity>
}
class Builder<TEntity extends IDbRecord> implements IBuilder<TEntity> {
defaults(value: DeepPartial<TEntity>): IBuilder<TEntity> {
return this;
}
}
interface IBaseEntity extends IDbRecord {
SyncCount: number;
SyncStatus: string
}
interface ICar extends IBaseEntity {
Model: string;
}
interface IPerson extends IBaseEntity {
Name: string
}
class Test {
protected builder<TEntity extends IDbRecord>() {
return new Builder<TEntity>();
}
private works<T extends IBaseEntity>() {
// not using the generic type works
return this.builder<IBaseEntity>().defaults({ SyncCount: 0 })
}
private doesNotWork<T extends IBaseEntity>() {
// using the generic type does not work here
return this.builder<T>().defaults({ SyncCount: 0 }) // ERROR
}
private someWorkingImplmentation<T extends IBaseEntity>() {
return this.builder<T>().defaults({ SyncCount: 0 });
}
// I want to avoid duplicate code below from defaults.
// A base setup method would be best
people = this.builder<IPerson>().defaults({ SyncCount: 0 });
cars = this.builder<ICar>().defaults({ SyncCount: 0 });
// GOAL
_people = this.someWorkingImplmentation<IPerson>();
_cars = this.someWorkingImplmentation<ICar>();
}