【发布时间】:2019-09-29 22:20:39
【问题描述】:
有没有更好的方法来做到这一点?我正在尝试编写一个静态工厂函数,它接受两个参数:一个通用对象和一个类类型,并返回给定类类型的一个新实例(或部分)。我想要检查通用对象的属性是否违反了类的公共属性的类型或名称。
由于它是一个静态函数,我无法在工厂类中定义新的返回类型。所以我试图依赖访问 ['prototype'] 就好像它是一个枚举。这是一个明智的方法吗?此外,似乎我需要扩展某些东西的 typeof 以使编译器能够访问“原型”属性。我想知道是否可以在保持导入函数静态的同时以更好的方式编写...?
export class emptyClass {
//intentionally empty. Can we get rid of this somehow? If so, what would T extend?
}
export class Person {
public id:number;
public name:string;
}
export class ImportObject<A> {
public static ImportCastStatic<U,T extends typeof emptyClass>(
untypedObject:{[K in keyof T['prototype']]?:T['prototype'][K]},
targetType:T)
:T['prototype'] {
let typedObject:T['prototype'] = <T['prototype']>new targetType();
return (typedObject);
}
}
export class Main {
constructor() {
//This is how I want to call it.
let q = ImportObject.ImportCastStatic({name:"Alice",id:3}, Person);
}
}
【问题讨论】:
标签: typescript typescript-generics